From 475f90bc6bcb7a20c846176716291e46a226d882 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Thu, 12 Oct 2017 17:43:49 -0700 Subject: [PATCH] Update LKG --- lib/enu/diagnosticMessages.generated.json.lcg | 46 +- lib/lib.d.ts | 66 +- lib/lib.es2015.core.d.ts | 2 + lib/lib.es2017.object.d.ts | 4 +- lib/lib.es5.d.ts | 66 +- lib/lib.es6.d.ts | 68 +- lib/tsc.js | 696 +++--- lib/tsserver.js | 1747 +++++++++++---- lib/tsserverlibrary.d.ts | 28 +- lib/tsserverlibrary.js | 1967 +++++++++++++---- lib/typescript.d.ts | 14 +- lib/typescript.js | 1750 +++++++++++---- lib/typescriptServices.d.ts | 14 +- lib/typescriptServices.js | 1750 +++++++++++---- lib/typingsInstaller.js | 193 +- 15 files changed, 6314 insertions(+), 2097 deletions(-) diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 0fb9549146a..0eb14ef956f 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -963,6 +963,12 @@ + + + + + + @@ -1229,7 +1235,7 @@ - + @@ -1305,6 +1311,12 @@ + + + + + + @@ -2469,6 +2481,18 @@ + + + + + + + + + + + + @@ -2595,15 +2619,15 @@ - + - + - + - + @@ -4725,6 +4749,12 @@ + + + + + + @@ -5043,6 +5073,12 @@ + + + + + + diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 5173d2ae390..788fa2613c7 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -1070,7 +1070,8 @@ interface ReadonlyArray { * @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: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; /** * 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. @@ -1082,7 +1083,8 @@ interface ReadonlyArray { * @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: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; /** * 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. @@ -1220,7 +1222,8 @@ interface Array { * @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: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): 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; /** * 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. @@ -1232,7 +1235,8 @@ interface Array { * @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: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + 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; /** * 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. @@ -1667,7 +1671,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1691,7 +1696,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -1934,7 +1940,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1958,7 +1965,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2201,7 +2209,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2225,7 +2234,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2466,7 +2476,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2490,7 +2501,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2734,7 +2746,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2758,7 +2771,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3001,7 +3015,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3025,7 +3040,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3267,7 +3283,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3291,7 +3308,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3534,7 +3552,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3558,7 +3577,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3802,7 +3822,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3826,7 +3847,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. diff --git a/lib/lib.es2015.core.d.ts b/lib/lib.es2015.core.d.ts index 0472b6080d9..f772b964beb 100644 --- a/lib/lib.es2015.core.d.ts +++ b/lib/lib.es2015.core.d.ts @@ -30,6 +30,7 @@ interface Array { * @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: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined; find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined; /** @@ -370,6 +371,7 @@ interface ReadonlyArray { * @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: (this: void, value: T, index: number, obj: ReadonlyArray) => value is S, thisArg?: any): S | undefined; find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; /** diff --git a/lib/lib.es2017.object.d.ts b/lib/lib.es2017.object.d.ts index 7eecc25680d..c0f782464ff 100644 --- a/lib/lib.es2017.object.d.ts +++ b/lib/lib.es2017.object.d.ts @@ -23,7 +23,7 @@ interface ObjectConstructor { * Returns an array of values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - values(o: { [s: string]: T }): T[]; + values(o: { [s: string]: T } | { [n: number]: T }): T[]; /** * Returns an array of values of the enumerable properties of an object @@ -35,7 +35,7 @@ interface ObjectConstructor { * Returns an array of key/values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - entries(o: { [s: string]: T }): [string, T][]; + entries(o: { [s: string]: T } | { [n: number]: T }): [string, T][]; /** * Returns an array of key/values of the enumerable properties of an object diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 73aa450927d..a554378e83e 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1070,7 +1070,8 @@ interface ReadonlyArray { * @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: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; /** * 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. @@ -1082,7 +1083,8 @@ interface ReadonlyArray { * @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: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; /** * 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. @@ -1220,7 +1222,8 @@ interface Array { * @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: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): 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; /** * 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. @@ -1232,7 +1235,8 @@ interface Array { * @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: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + 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; /** * 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. @@ -1667,7 +1671,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1691,7 +1696,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -1934,7 +1940,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1958,7 +1965,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2201,7 +2209,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2225,7 +2234,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2466,7 +2476,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2490,7 +2501,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2734,7 +2746,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2758,7 +2771,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3001,7 +3015,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3025,7 +3040,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3267,7 +3283,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3291,7 +3308,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3534,7 +3552,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3558,7 +3577,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3802,7 +3822,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3826,7 +3847,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 99cc37b759c..ccd9acef948 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -1070,7 +1070,8 @@ interface ReadonlyArray { * @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: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; /** * 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. @@ -1082,7 +1083,8 @@ interface ReadonlyArray { * @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: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; /** * 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. @@ -1220,7 +1222,8 @@ interface Array { * @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: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): 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; /** * 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. @@ -1232,7 +1235,8 @@ interface Array { * @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: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + 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; /** * 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. @@ -1667,7 +1671,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1691,7 +1696,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -1934,7 +1940,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1958,7 +1965,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2201,7 +2209,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2225,7 +2234,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2466,7 +2476,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2490,7 +2501,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2734,7 +2746,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2758,7 +2771,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3001,7 +3015,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3025,7 +3040,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3267,7 +3283,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3291,7 +3308,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3534,7 +3552,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3558,7 +3577,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3802,7 +3822,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3826,7 +3847,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -4094,6 +4116,7 @@ interface Array { * @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: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined; find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined; /** @@ -4434,6 +4457,7 @@ interface ReadonlyArray { * @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: (this: void, value: T, index: number, obj: ReadonlyArray) => value is S, thisArg?: any): S | undefined; find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; /** diff --git a/lib/tsc.js b/lib/tsc.js index 57e2f035ec6..23c5e182860 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -152,7 +152,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.6"; - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -302,10 +302,12 @@ var ts; } ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { + var result = []; Debug.assert(arrayA.length === arrayB.length); for (var i = 0; i < arrayA.length; i++) { - callback(arrayA[i], arrayB[i], i); + result.push(callback(arrayA[i], arrayB[i], i)); } + return result; } ts.zipWith = zipWith; function zipToMap(keys, values) { @@ -424,22 +426,6 @@ var ts; return array; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var item = array_2[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var i = 0; i < array.length; i++) { @@ -490,8 +476,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -655,8 +641,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (predicate(v)) { return true; } @@ -681,8 +667,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + loop: for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -770,8 +756,8 @@ var ts; ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result += v[prop]; } return result; @@ -1071,8 +1057,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; @@ -1480,7 +1466,7 @@ var ts; } ts.getDirectoryPath = getDirectoryPath; function isUrl(path) { - return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + return path && !isRootedDiskPath(path) && stringContains(path, "://"); } ts.isUrl = isUrl; function pathIsRelative(path) { @@ -1709,8 +1695,12 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; function hasExtension(fileName) { - return getBaseFileName(fileName).indexOf(".") >= 0; + return stringContains(getBaseFileName(fileName), "."); } ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { @@ -3098,6 +3088,7 @@ var ts; Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), 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."), @@ -3425,6 +3416,7 @@ var ts; A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), 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}'."), @@ -3748,9 +3740,10 @@ var ts; Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), - JSDoc_augments_is_not_attached_to_a_class_declaration: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_augments_is_not_attached_to_a_class_declaration_8022", "JSDoc '@augments' is not attached to a class declaration."), - JSDoc_augments_0_does_not_match_the_extends_1_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023", "JSDoc '@augments {0}' does not match the 'extends {1}' clause."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), 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."), @@ -3782,7 +3775,7 @@ 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(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), - Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'."), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), @@ -3796,6 +3789,7 @@ var ts; Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'."), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), @@ -3804,6 +3798,8 @@ var ts; Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Infer_type_of_0_from_usage: diag(95009, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95009", "Infer type of '{0}' from usage."), + Infer_parameter_types_from_usage: diag(95010, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95010", "Infer parameter types from usage."), }; })(ts || (ts = {})); var ts; @@ -6760,27 +6756,14 @@ var ts; } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { - return isRestParameter(ts.lastOrUndefined(s.parameters)); + var last = ts.lastOrUndefined(s.parameters); + return last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; - function hasDeclaredRestParameter(s) { - return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); - } - ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 274 || - ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { - return true; - } - } - return isDeclaredRestParam(node); + return node.dotDotDotToken !== undefined; } ts.isRestParameter = isRestParameter; - function isDeclaredRestParam(node) { - return node && node.dotDotDotToken !== undefined; - } - ts.isDeclaredRestParam = isDeclaredRestParam; function getAssignmentTargetKind(node) { var parent = node.parent; while (true) { @@ -8707,27 +8690,35 @@ var ts; if (!declaration) { return undefined; } - if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143) { - return declaration.name.right; - } - if (declaration.kind === 194) { - var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { - case 1: - case 4: - case 5: - case 3: - return expr.left.name; - default: - return undefined; + switch (declaration.kind) { + case 284: + case 279: { + var name = declaration.name; + if (name.kind === 143) { + return name.right; + } + break; + } + case 194: { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + default: + return undefined; + } + } + case 283: + return getNameOfJSDocTypedef(declaration); + case 243: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; } } - else if (declaration.kind === 283) { - return getNameOfJSDocTypedef(declaration); - } - else { - return declaration.name; - } + return declaration.name; } ts.getNameOfDeclaration = getNameOfDeclaration; function getJSDocParameterTags(param) { @@ -8794,6 +8785,11 @@ var ts; var tags = getJSDocTags(node); return ts.find(tags, function (doc) { return doc.kind === kind; }); } + function getAllJSDocTagsOfKind(node, kind) { + var tags = getJSDocTags(node); + return ts.filter(tags, function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); (function (ts) { function isNumericLiteral(node) { @@ -10028,6 +10024,14 @@ var ts; return node.kind >= 276 && node.kind <= 285; } ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 154; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 153; + } + ts.isGetAccessor = isGetAccessor; function hasJSDocNodes(node) { return !!node.jsDoc && node.jsDoc.length > 0; } @@ -14565,6 +14569,7 @@ var ts; if (tagName) { switch (tagName.escapedText) { case "augments": + case "extends": tag = parseAugmentsTag(atToken, tagName); break; case "class": @@ -14849,7 +14854,7 @@ var ts; if (typeExpression && typeExpression.type.kind === 164) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); } @@ -15074,8 +15079,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var node = array_7[_i]; visitNode(node); } } @@ -15147,8 +15152,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } return; @@ -15373,6 +15378,9 @@ var ts; var reportedUnreachableFlow = { flags: 1 }; var subtreeTransformFlags = 0; var skipTransformFlagAggregation; + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } function bindSourceFile(f, opts) { file = f; options = opts; @@ -15443,6 +15451,9 @@ var ts; } } function getDeclarationName(node) { + if (node.kind === 243) { + return node.isExportEquals ? "export=" : "default"; + } var name = ts.getNameOfDeclaration(node); if (name) { if (ts.isAmbientModule(node)) { @@ -15472,8 +15483,6 @@ var ts; return "__index"; case 244: return "__export"; - case 243: - return node.isExportEquals ? "export=" : "default"; case 194: if (ts.getSpecialPropertyAssignmentKind(node) === 2) { return "export="; @@ -15542,9 +15551,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -16196,7 +16205,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } if (!node.statement || node.statement.kind !== 212) { addAntecedent(postStatementLabel, currentFlow); @@ -16622,7 +16631,7 @@ var ts; !ts.isIdentifierName(node) && !ts.isInAmbientContext(node)) { if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); } } } @@ -16698,7 +16707,7 @@ var ts; } function checkStrictModeNumericLiteral(node) { if (inStrictMode && node.numericLiteralFlags & 4) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } function checkStrictModePostfixUnaryExpression(node) { @@ -16942,7 +16951,7 @@ var ts; } case 284: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 272 ? 4 | 16777216 : 4; return declareSymbolAndAddToSymbolTable(propTag, flags, 0); @@ -16993,20 +17002,20 @@ var ts; } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } if (node.parent.kind !== 265) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { var parent_1 = node.parent; if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } } @@ -17041,15 +17050,12 @@ var ts; function isExportsOrModuleExportsOrAlias(node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); } function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (ts.isIdentifier(node)) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - return false; + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(node) { return isExportsOrModuleExportsOrAlias(node) || @@ -17096,13 +17102,15 @@ var ts; function bindStaticPropertyAssignment(node) { var leftSideOfAssignment = node.left; var target = leftSideOfAssignment.expression; - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); + if (ts.isIdentifier(target)) { + leftSideOfAssignment.parent = node; + target.parent = leftSideOfAssignment; + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); + } } } function lookupSymbolForName(name) { @@ -17144,7 +17152,7 @@ var ts; if (node.name) { node.name.parent = node; } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); } symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); prototypeSymbol.parent = symbol; @@ -17324,6 +17332,9 @@ var ts; } if (expression.kind === 91) { transformFlags |= 67108864; + if (subtreeFlags & 16384) { + transformFlags |= 32768; + } } node.transformFlags = transformFlags | 536870912; return transformFlags & ~537396545; @@ -18823,7 +18834,7 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : withoutAtTypePrefix; } @@ -19085,6 +19096,23 @@ var ts; return tryFindAmbientModule(moduleName, false); }, getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getBooleanType: function () { return booleanType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, isArrayLikeType: isArrayLikeType, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, @@ -19130,6 +19158,7 @@ var ts; anyFunctionType.flags |= 8388608; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var markerSuperType = createType(16384); var markerSubType = createType(16384); markerSubType.constraint = markerSuperType; @@ -19564,6 +19593,7 @@ var ts; var originalLocation = location; var result; var lastLocation; + var lastNonBlockLocation; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; @@ -19713,10 +19743,13 @@ var ts; } break; } + if (location.kind !== 207) { + lastNonBlockLocation = location; + } lastLocation = location; location = location.parent; } - if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; } if (!result) { @@ -22147,10 +22180,10 @@ var ts; if (parentType === unknownType) { return unknownType; } - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { return parentType; } var type; @@ -22174,9 +22207,6 @@ var ts; if (isComputedNonLiteralName(name)) { return anyType; } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } var text = ts.getTextOfPropertyName(name); var declaredType = getTypeOfPropertyOfType(parentType, text); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || @@ -23723,18 +23753,35 @@ var ts; function getApparentTypeOfIntersectionType(type) { return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); } - function getDefaultFromTypeParameter(typeParameter) { + function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; } else { + typeParameter.default = resolvingDefaultType; var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + typeParameter.default = defaultType; + } } } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + else if (typeParameter.default === resolvingDefaultType) { + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } + function getDefaultFromTypeParameter(typeParameter) { + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } function getApparentType(type) { var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; @@ -23870,7 +23917,7 @@ var ts; return getIndexTypeOfStructuredType(getApparentType(type), kind); } function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { + if (isObjectTypeWithInferableIndex(type)) { var propTypes = []; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; @@ -23967,7 +24014,7 @@ var ts; var minTypeArgumentCount = 0; if (typeParameters) { for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { + if (!hasTypeParameterDefault(typeParameters[i])) { minTypeArgumentCount = i + 1; } } @@ -25165,7 +25212,7 @@ var ts; var symbol = getAliasSymbolForTypeNode(node); return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } - function getSpreadType(left, right) { + function getSpreadType(left, right, symbol, propagatedFlags) { if (left.flags & 1 || right.flags & 1) { return anyType; } @@ -25176,10 +25223,10 @@ var ts; return left; } if (left.flags & 65536) { - return mapType(left, function (t) { return getSpreadType(t, right); }); + return mapType(left, function (t) { return getSpreadType(t, right, symbol, propagatedFlags); }); } if (right.flags & 65536) { - return mapType(right, function (t) { return getSpreadType(left, t); }); + return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } if (right.flags & 16777216) { return nonPrimitiveType; @@ -25234,7 +25281,12 @@ var ts; members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); } } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var spread = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; + spread.symbol = symbol; + return spread; } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { @@ -25517,7 +25569,7 @@ var ts; var declaration_1 = symbol.declarations[0]; var outerTypeParameters = getOuterTypeParameters(declaration_1, true) || ts.emptyArray; typeParameters = symbol.flags & 2048 && !target.aliasTypeArguments ? - ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : outerTypeParameters; links.typeParameters = typeParameters; if (typeParameters.length) { @@ -25539,13 +25591,24 @@ var ts; } return type; } - function isTypeParameterReferencedWithin(tp, node) { - return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); - function checkThis(node) { - return node.kind === 169 || ts.forEachChild(node, checkThis); + function isTypeParameterPossiblyReferenced(tp, node) { + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_1 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 207 ? "quit" : n === container_1; })) { + return ts.forEachChild(node, containsReference); + } } - function checkIdentifier(node) { - return node.kind === 71 && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + return true; + function containsReference(node) { + switch (node.kind) { + case 169: + return tp.isThisType; + case 71: + return !tp.isThisType && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp; + case 162: + return true; + } + return ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -25711,9 +25774,9 @@ var ts; return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, false, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; + return compareSignaturesRelated(source, target, 0, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; } - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { if (source === target) { return -1; } @@ -25725,7 +25788,7 @@ var ts; source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } var kind = target.declaration ? target.declaration.kind : 0; - var strictVariance = strictFunctionTypes && kind !== 151 && + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 151 && kind !== 150 && kind !== 152; var result = -1; var sourceThisType = getThisTypeOfSignature(source); @@ -25751,13 +25814,13 @@ var ts; for (var i = 0; i < checkCount; i++) { var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && (getFalsyFlags(sourceType) & 6144) === (getFalsyFlags(targetType) & 6144); var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, true, false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && !strictVariance && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 : 1, false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.symbolName(sourceParams[i < sourceMax ? i : sourceMax]), ts.symbolName(targetParams[i < targetMax ? i : targetMax])); @@ -25784,7 +25847,7 @@ var ts; } } else { - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, false) || + result &= callbackCheck === 1 && compareTypes(targetReturnType, sourceReturnType, false) || compareTypes(sourceReturnType, targetReturnType, reportErrors); } } @@ -26141,6 +26204,12 @@ var ts; (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } + if (target.flags & 65536) { + var discriminantType = findMatchingDiscriminantType(source, target); + if (discriminantType) { + return hasExcessProperties(source, discriminantType, reportErrors); + } + } var _loop_4 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -26211,22 +26280,25 @@ var ts; return 0; } function findMatchingDiscriminantType(source, target) { + var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.escapedName)) { - 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)) { - return type; + var sourceProperty = findSingleDiscriminantProperty(sourceProperties, target); + if (sourceProperty) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var type = _a[_i]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); + if (targetType && isRelatedTo(sourceType, targetType)) { + if (match) { + return undefined; } + match = type; } } } } + return match; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1; @@ -26611,8 +26683,8 @@ var ts; return 0; } var result = -1; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); if (!targetProp) { return 0; @@ -26683,7 +26755,7 @@ var ts; return result; } function signatureRelatedTo(source, target, erase, reportErrors) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, false, false, reportErrors, reportError, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0, false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -26741,7 +26813,7 @@ var ts; if (isGenericMappedType(source)) { return kind === 0 && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); } - if (isObjectLiteralType(source)) { + if (isObjectTypeWithInferableIndex(source)) { var related = -1; if (kind === 0) { var sourceNumberInfo = getIndexInfoOfType(source, 1); @@ -27128,8 +27200,8 @@ var ts; function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; } - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 | 2048)) !== 0 && + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 | 2048 | 512)) !== 0 && getSignaturesOfType(type, 0).length === 0 && getSignaturesOfType(type, 1).length === 0; } @@ -27836,6 +27908,19 @@ var ts; } return false; } + function findSingleDiscriminantProperty(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + return undefined; + } + result = sourceProperty; + } + } + return result; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -29897,7 +29982,7 @@ var ts; checkExternalEmitHelpers(memberDecl, 2); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -29909,7 +29994,7 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return unknownType; } - spread = getSpreadType(spread, type); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags); offset = i + 1; continue; } @@ -29944,13 +30029,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768) { - spread.flags |= propagatedFlags; - spread.flags |= 1048576; - spread.objectFlags |= 128; - spread.symbol = node.symbol; + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); } return spread; } @@ -29995,7 +30074,7 @@ var ts; return getJsxGlobalElementType() || anyType; } function isUnhyphenatedJsxName(name) { - return name.indexOf("-") < 0; + return !ts.stringContains(name, "-"); } function isJsxIntrinsicIdentifier(tagName) { switch (tagName.kind) { @@ -30041,7 +30120,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 255); if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, 0); attributesArray = []; attributesTable = ts.createSymbolTable(); } @@ -30050,7 +30129,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 0); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -30060,7 +30139,7 @@ var ts; if (!hasSpreadAnyType) { if (spread !== emptyObjectType) { if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, 0); } attributesArray = getPropertiesOfType(spread); } @@ -31101,29 +31180,27 @@ var ts; } return getInferredTypes(context); } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJavaScriptFile(signature.declaration); var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } + 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 && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + 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; } } - return typeArgumentsAreAssignable; + return typeArgumentTypes; } function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { var callIsIncomplete = node.attributes.end === node.end; @@ -31400,8 +31477,7 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - var typeArguments_1 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, fallbackError); + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -31443,14 +31519,14 @@ var ts; var candidate = candidates[bestIndex]; var typeParameters = candidate.typeParameters; if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_2 = node.typeArguments.map(getTypeOfNode); - while (typeArguments_2.length > typeParameters.length) { - typeArguments_2.pop(); + var typeArguments_1 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_1.length > typeParameters.length) { + typeArguments_1.pop(); } - while (typeArguments_2.length < typeParameters.length) { - typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + while (typeArguments_1.length < typeParameters.length) { + typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); } - var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + var instantiated = createSignatureInstantiation(candidate, typeArguments_1); candidates[bestIndex] = instantiated; return instantiated; } @@ -31485,10 +31561,12 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); - if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { + var typeArgumentResult = checkTypeArguments(candidate, typeArguments, false); + if (typeArgumentResult) { + typeArgumentTypes = typeArgumentResult; + } + else { candidateForTypeArgumentError = originalCandidate; break; } @@ -31496,6 +31574,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { @@ -31712,6 +31791,11 @@ var ts; if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; @@ -31722,6 +31806,13 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); } + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getEffectiveArgumentCount(decorator, undefined, signature); + }); + } function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { ts.Debug.assert(!(elementType.flags & 65536)); return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); @@ -33163,6 +33254,9 @@ var ts; if (!hasNonCircularBaseConstraint(typeParameter)) { error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } var constraintType = getConstraintOfTypeParameter(typeParameter); var defaultType = getDefaultFromTypeParameter(typeParameter); if (constraintType && defaultType) { @@ -33177,7 +33271,6 @@ var ts; checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92)) { - func = ts.getContainingFunction(node); if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } @@ -34278,17 +34371,22 @@ var ts; } } function checkJSDocAugmentsTag(node) { - var cls = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(cls) && !ts.isClassExpression(cls)) { - error(cls, ts.Diagnostics.JSDoc_augments_is_not_attached_to_a_class_declaration); + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } + var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 277); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } var name = getIdentifierFromEntityNameExpression(node.class.expression); - var extend = ts.getClassExtendsHeritageClauseElement(cls); + var extend = ts.getClassExtendsHeritageClauseElement(classLike); if (extend) { var className = getIdentifierFromEntityNameExpression(extend.expression); if (className && name.escapedText !== className.escapedText) { - error(name, ts.Diagnostics.JSDoc_augments_0_does_not_match_the_extends_1_clause, ts.idText(name), ts.idText(className)); + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); } } } @@ -34513,7 +34611,7 @@ var ts; } } function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -38625,6 +38723,9 @@ var ts; } ts.createNodeArray = createNodeArray; function getSynthesizedClone(node) { + if (node === undefined) { + return undefined; + } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; setOriginalNode(clone, node); @@ -40804,6 +40905,12 @@ var ts; return node; } ts.setEmitFlags = setEmitFlags; + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; function getSourceMapRange(node) { var emitNode = node.emitNode; return (emitNode && emitNode.sourceMapRange) || node; @@ -43060,6 +43167,14 @@ var ts; } return values; } + function isSimpleCopiableExpression(expression) { + return expression.kind === 9 || + expression.kind === 8 || + expression.kind === 13 || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; })(ts || (ts = {})); var ts; (function (ts) { @@ -43387,6 +43502,7 @@ var ts; var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = typeof compilerOptions.strictNullChecks === "undefined" ? compilerOptions.strict : compilerOptions.strictNullChecks; var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); var previousOnEmitNode = context.onEmitNode; @@ -43659,7 +43775,8 @@ var ts; var facts = 0; if (ts.some(staticProperties)) facts |= 1; - if (ts.getClassExtendsHeritageClauseElement(node)) + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95) facts |= 64; if (shouldEmitDecorateCallForClass(node)) facts |= 2; @@ -43784,16 +43901,16 @@ var ts; } return classExpression; } - function transformClassMembers(node, hasExtendsClause) { + function transformClassMembers(node, isDerivedClass) { var members = []; - var constructor = transformConstructor(node, hasExtendsClause); + var constructor = transformConstructor(node, isDerivedClass); if (constructor) { members.push(constructor); } ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); return ts.setTextRange(ts.createNodeArray(members), node.members); } - function transformConstructor(node, hasExtendsClause) { + function transformConstructor(node, isDerivedClass) { var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); var hasParameterPropertyAssignments = node.transformFlags & 262144; var constructor = ts.getFirstConstructorWithBody(node); @@ -43801,14 +43918,14 @@ var ts; return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause); + var body = transformConstructorBody(node, constructor, isDerivedClass); return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(undefined, undefined, parameters, body), constructor || node), constructor)); } function transformConstructorParameters(constructor) { return ts.visitParameterList(constructor && constructor.parameters, visitor, context) || []; } - function transformConstructorBody(node, constructor, hasExtendsClause) { + function transformConstructorBody(node, constructor, isDerivedClass) { var statements = []; var indexOfFirstStatement = 0; resumeLexicalEnvironment(); @@ -43817,7 +43934,7 @@ var ts; var propertyAssignments = getParametersWithPropertyAssignments(constructor); ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); } - else if (hasExtendsClause) { + else if (isDerivedClass) { statements.push(ts.createStatement(ts.createCall(ts.createSuper(), undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); } var properties = getInitializedProperties(node, false); @@ -44258,6 +44375,15 @@ var ts; var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 168) { + typeNode = typeNode.type; + } + if (typeNode.kind === 130) { + continue; + } + if (!strictNullChecks && (typeNode.kind === 95 || typeNode.kind === 139)) { + continue; + } var serializedIndividual = serializeTypeNode(typeNode); if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { return serializedIndividual; @@ -44273,7 +44399,7 @@ var ts; serializedUnion = serializedIndividual; } } - return serializedUnion; + return serializedUnion || ts.createVoidZero(); } function serializeTypeReferenceNode(node) { switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { @@ -48752,7 +48878,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { - if (ts.forEach(node.arguments, containsYield)) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, true), target = _a.target, thisArg = _a.thisArg; return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), node), node); } @@ -49928,7 +50054,7 @@ var ts; default: return transformCommonJSModule; } } - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -50144,28 +50270,65 @@ var ts; } } function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var containsLexicalThis = !!(node.transformFlags & 16384); switch (compilerOptions.module) { case ts.ModuleKind.AMD: - return transformImportCallExpressionAMD(node); + return createImportCallExpressionAMD(argument, containsLexicalThis); case ts.ModuleKind.UMD: - return transformImportCallExpressionUMD(node); + return createImportCallExpressionUMD(argument, containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return transformImportCallExpressionCommonJS(node); + return createImportCallExpressionCommonJS(argument, containsLexicalThis); } } - function transformImportCallExpressionUMD(node) { + function createImportCallExpressionUMD(arg, containsLexicalThis) { needUMDDynamicImportHelper = true; - return ts.createConditional(ts.createIdentifier("__syncRequire"), transformImportCallExpressionCommonJS(node), transformImportCallExpressionAMD(node)); + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536); + return ts.createConditional(ts.createIdentifier("__syncRequire"), createImportCallExpressionCommonJS(arg, containsLexicalThis), createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(ts.createIdentifier("__syncRequire"), createImportCallExpressionCommonJS(temp, containsLexicalThis), createImportCallExpressionAMD(temp, containsLexicalThis))); + } } - function transformImportCallExpressionAMD(node) { + function createImportCallExpressionAMD(arg, containsLexicalThis) { var resolve = ts.createUniqueName("resolve"); var reject = ts.createUniqueName("reject"); - return ts.createNew(ts.createIdentifier("Promise"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, resolve), - ts.createParameter(undefined, undefined, undefined, reject)], undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + var parameters = [ + ts.createParameter(undefined, undefined, undefined, resolve), + ts.createParameter(undefined, undefined, undefined, reject) + ]; + var body = ts.createBlock([ + ts.createStatement(ts.createCall(ts.createIdentifier("require"), undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2) { + func = ts.createArrowFunction(undefined, undefined, parameters, undefined, undefined, body); + } + else { + func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, parameters, undefined, body); + if (containsLexicalThis) { + ts.setEmitFlags(func, 8); + } + } + return ts.createNew(ts.createIdentifier("Promise"), undefined, [func]); } - function transformImportCallExpressionCommonJS(node) { - return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []), "then"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, undefined, undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), undefined, node.arguments))]))]); + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []); + var requireCall = ts.createCall(ts.createIdentifier("require"), undefined, arg ? [arg] : []); + var func; + if (languageVersion >= 2) { + func = ts.createArrowFunction(undefined, undefined, [], undefined, undefined, requireCall); + } + else { + func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [], undefined, ts.createBlock([ts.createReturn(requireCall)])); + if (containsLexicalThis) { + ts.setEmitFlags(func, 8); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), undefined, [func]); } function visitImportDeclaration(node) { var statements; @@ -50268,10 +50431,10 @@ var ts; var original = node.original; if (original && hasAssociatedEndOfDeclarationMarker(original)) { var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, node, true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), node, true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, node, true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), node, true); } return ts.singleOrMany(statements); } @@ -51296,7 +51459,7 @@ var ts; } } function visitImportCallExpression(node) { - return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), undefined, node.arguments); + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); } function visitDestructuringAssignment(node) { if (hasExportedReferenceInDestructuringTarget(node.left)) { @@ -52507,7 +52670,7 @@ var ts; }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); - return comment.indexOf("@internal") >= 0; + return ts.stringContains(comment, "@internal"); } function stripInternal(node) { if (node) { @@ -54924,7 +55087,7 @@ var ts; if (ts.isNumericLiteral(expression)) { var text = getLiteralTextOfNode(expression); return !expression.numericLiteralFlags - && text.indexOf(ts.tokenToString(23)) < 0; + && !ts.stringContains(text, ts.tokenToString(23)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); @@ -56377,18 +56540,28 @@ var ts; ts.addFileWatcher = addFileWatcher; function addFileWatcherWithLogging(host, file, cb, log) { var watcherCaption = "FileWatcher:: "; - return createWatcherWithLogging(addFileWatcher, watcherCaption, log, host, file, cb); + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, false, host, file, cb); } ts.addFileWatcherWithLogging = addFileWatcherWithLogging; + function addFileWatcherWithOnlyTriggerLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, true, host, file, cb); + } + ts.addFileWatcherWithOnlyTriggerLogging = addFileWatcherWithOnlyTriggerLogging; function addFilePathWatcher(host, file, cb, path) { return host.watchFile(file, function (fileName, eventKind) { return cb(fileName, eventKind, path); }); } ts.addFilePathWatcher = addFilePathWatcher; function addFilePathWatcherWithLogging(host, file, cb, path, log) { var watcherCaption = "FileWatcher:: "; - return createWatcherWithLogging(addFileWatcher, watcherCaption, log, host, file, cb, path); + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, false, host, file, cb, path); } ts.addFilePathWatcherWithLogging = addFilePathWatcherWithLogging; + function addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, true, host, file, cb, path); + } + ts.addFilePathWatcherWithOnlyTriggerLogging = addFilePathWatcherWithOnlyTriggerLogging; function addDirectoryWatcher(host, directory, cb, flags) { var recursive = (flags & 1) !== 0; return host.watchDirectory(directory, cb, recursive); @@ -56396,12 +56569,19 @@ var ts; ts.addDirectoryWatcher = addDirectoryWatcher; function addDirectoryWatcherWithLogging(host, directory, cb, flags, log) { var watcherCaption = "DirectoryWatcher " + ((flags & 1) !== 0 ? "recursive" : "") + ":: "; - return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, host, directory, cb, flags); + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, false, host, directory, cb, flags); } ts.addDirectoryWatcherWithLogging = addDirectoryWatcherWithLogging; - function createWatcherWithLogging(addWatch, watcherCaption, log, host, file, cb, optional) { + function addDirectoryWatcherWithOnlyTriggerLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, true, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithOnlyTriggerLogging = addDirectoryWatcherWithOnlyTriggerLogging; + function createWatcherWithLogging(addWatch, watcherCaption, log, logOnlyTrigger, host, file, cb, optional) { var info = "PathInfo: " + file; - log(watcherCaption + "Added: " + info); + if (!logOnlyTrigger) { + log(watcherCaption + "Added: " + info); + } var watcher = addWatch(host, file, function (fileName, cbOptional1) { var optionalInfo = cbOptional1 !== undefined ? " " + cbOptional1 : ""; log(watcherCaption + "Trigger: " + fileName + optionalInfo + " " + info); @@ -56412,7 +56592,9 @@ var ts; }, optional); return { close: function () { - log(watcherCaption + "Close: " + info); + if (!logOnlyTrigger) { + log(watcherCaption + "Close: " + info); + } watcher.close(); } }; @@ -56499,8 +56681,7 @@ var ts; existingInfo.version = sourceFile.version; emitHandler.onUpdateSourceFile(program, sourceFile); } - else if (program.hasInvalidatedResolution(sourceFile.path) && - emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { + else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { registerChangedFile(sourceFile.path, sourceFile.fileName); } } @@ -57264,8 +57445,7 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, - hasInvalidatedResolution: hasInvalidatedResolution + redirectTargetsSet: redirectTargetsSet }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -57557,10 +57737,15 @@ var ts; if (file.hasNoDefaultLib) { return true; } - if (defaultLibraryPath && defaultLibraryPath.length !== 0) { - return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, !host.useCaseSensitiveFileNames()); + if (!options.noLib) { + return false; + } + if (!options.lib) { + return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), !host.useCaseSensitiveFileNames()) === 0; + } + else { + return ts.forEach(options.lib, function (libFileName) { return ts.compareStrings(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName), !host.useCaseSensitiveFileNames()) === 0; }); } - return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), !host.useCaseSensitiveFileNames()) === 0; } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); @@ -58573,7 +58758,7 @@ var ts; return { startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, - startCachingPerDirectoryResolution: startCachingPerDirectoryResolution, + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, @@ -58603,7 +58788,7 @@ var ts; resolvedModuleNames.clear(); resolvedTypeReferenceDirectives.clear(); allFilesHaveInvalidatedResolution = false; - ts.Debug.assert(perDirectoryResolvedModuleNames.size === 0 && perDirectoryResolvedTypeReferenceDirectives.size === 0); + clearPerDirectoryResolutions(); } function startRecordingFilesWithChangedResolutions() { filesWithChangedSetOfUnresolvedImports = []; @@ -58622,8 +58807,9 @@ var ts; filesWithInvalidatedResolutions = undefined; return function (path) { return collected && collected.has(path); }; } - function startCachingPerDirectoryResolution() { - ts.Debug.assert(perDirectoryResolvedModuleNames.size === 0 && perDirectoryResolvedTypeReferenceDirectives.size === 0); + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); } function finishCachingPerDirectoryResolution() { allFilesHaveInvalidatedResolution = false; @@ -58633,8 +58819,7 @@ var ts; watcher.watcher.close(); } }); - perDirectoryResolvedModuleNames.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); @@ -58737,14 +58922,11 @@ var ts; } var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); var dirPath = ts.getDirectoryPath(failedLookupLocationPath); - if (isNodeModulesDirectory(dirPath)) { - return { dir: dir, dirPath: dirPath }; + while (ts.stringContains(dirPath, "/node_modules/")) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); } - if (dirPath.indexOf("/node_modules/") !== -1) { - while (!isNodeModulesDirectory(dirPath)) { - dir = ts.getDirectoryPath(dir); - dirPath = ts.getDirectoryPath(dirPath); - } + if (isNodeModulesDirectory(dirPath)) { return { dir: dir, dirPath: dirPath }; } if (rootPath !== undefined) { @@ -59132,10 +59314,10 @@ var ts; var hasChangedCompilerOptions = false; var hasChangedAutomaticTypeDirectiveNames = false; var loggingEnabled = compilerOptions.diagnostics || compilerOptions.extendedDiagnostics; - var writeLog = loggingEnabled ? function (s) { return system.write(s); } : ts.noop; - var watchFile = loggingEnabled ? ts.addFileWatcherWithLogging : ts.addFileWatcher; - var watchFilePath = loggingEnabled ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher; - var watchDirectoryWorker = loggingEnabled ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher; + var writeLog = loggingEnabled ? function (s) { system.write(s); system.write(system.newLine); } : ts.noop; + var watchFile = compilerOptions.extendedDiagnostics ? ts.addFileWatcherWithLogging : loggingEnabled ? ts.addFileWatcherWithOnlyTriggerLogging : ts.addFileWatcher; + var watchFilePath = compilerOptions.extendedDiagnostics ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher; + var watchDirectoryWorker = compilerOptions.extendedDiagnostics ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher; watchingHost = watchingHost || createWatchingSystemHost(compilerOptions.pretty); var system = watchingHost.system, parseConfigFile = watchingHost.parseConfigFile, reportDiagnostic = watchingHost.reportDiagnostic, reportWatchDiagnostic = watchingHost.reportWatchDiagnostic, beforeCompile = watchingHost.beforeCompile, afterCompile = watchingHost.afterCompile; var directoryStructureHost = configFileName ? ts.createCachedDirectoryStructureHost(system) : system; @@ -59190,17 +59372,17 @@ var ts; writeLog("Synchronizing program"); if (hasChangedCompilerOptions) { newLine = ts.getNewLineCharacter(compilerOptions, system); + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { + resolutionCache.clear(); + } } var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(); if (ts.isProgramUptoDate(program, rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { return; } - if (hasChangedCompilerOptions && ts.changesAffectModuleResolution(program && program.getCompilerOptions(), compilerOptions)) { - resolutionCache.clear(); - } + beforeCompile(compilerOptions); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; hasChangedCompilerOptions = false; - beforeCompile(compilerOptions); resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; diff --git a/lib/tsserver.js b/lib/tsserver.js index 32009252a01..f6e28be89c5 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -1177,7 +1177,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.6"; - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -1333,10 +1333,12 @@ var ts; } ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { + var result = []; Debug.assert(arrayA.length === arrayB.length); for (var i = 0; i < arrayA.length; i++) { - callback(arrayA[i], arrayB[i], i); + result.push(callback(arrayA[i], arrayB[i], i)); } + return result; } ts.zipWith = zipWith; function zipToMap(keys, values) { @@ -1455,22 +1457,6 @@ var ts; return array; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var item = array_2[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var i = 0; i < array.length; i++) { @@ -1521,8 +1507,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1686,8 +1672,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (predicate(v)) { return true; } @@ -1712,8 +1698,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + loop: for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -1801,8 +1787,8 @@ var ts; ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result += v[prop]; } return result; @@ -2102,8 +2088,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; @@ -2511,7 +2497,7 @@ var ts; } ts.getDirectoryPath = getDirectoryPath; function isUrl(path) { - return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + return path && !isRootedDiskPath(path) && stringContains(path, "://"); } ts.isUrl = isUrl; function pathIsRelative(path) { @@ -2740,8 +2726,12 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; function hasExtension(fileName) { - return getBaseFileName(fileName).indexOf(".") >= 0; + return stringContains(getBaseFileName(fileName), "."); } ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { @@ -4148,6 +4138,7 @@ var ts; Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), 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."), @@ -4475,6 +4466,7 @@ var ts; A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), 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}'."), @@ -4798,9 +4790,10 @@ var ts; Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), - JSDoc_augments_is_not_attached_to_a_class_declaration: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_augments_is_not_attached_to_a_class_declaration_8022", "JSDoc '@augments' is not attached to a class declaration."), - JSDoc_augments_0_does_not_match_the_extends_1_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023", "JSDoc '@augments {0}' does not match the 'extends {1}' clause."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), 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."), @@ -4832,7 +4825,7 @@ 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(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), - Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'."), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), @@ -4846,6 +4839,7 @@ var ts; Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'."), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), @@ -4854,6 +4848,8 @@ var ts; Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Infer_type_of_0_from_usage: diag(95009, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95009", "Infer type of '{0}' from usage."), + Infer_parameter_types_from_usage: diag(95010, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95010", "Infer parameter types from usage."), }; })(ts || (ts = {})); var ts; @@ -5599,7 +5595,7 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : withoutAtTypePrefix; } @@ -7018,27 +7014,14 @@ var ts; } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { - return isRestParameter(ts.lastOrUndefined(s.parameters)); + var last = ts.lastOrUndefined(s.parameters); + return last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; - function hasDeclaredRestParameter(s) { - return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); - } - ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 274 || - ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { - return true; - } - } - return isDeclaredRestParam(node); + return node.dotDotDotToken !== undefined; } ts.isRestParameter = isRestParameter; - function isDeclaredRestParam(node) { - return node && node.dotDotDotToken !== undefined; - } - ts.isDeclaredRestParam = isDeclaredRestParam; var AssignmentKind; (function (AssignmentKind) { AssignmentKind[AssignmentKind["None"] = 0] = "None"; @@ -8990,27 +8973,35 @@ var ts; if (!declaration) { return undefined; } - if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143) { - return declaration.name.right; - } - if (declaration.kind === 194) { - var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { - case 1: - case 4: - case 5: - case 3: - return expr.left.name; - default: - return undefined; + switch (declaration.kind) { + case 284: + case 279: { + var name = declaration.name; + if (name.kind === 143) { + return name.right; + } + break; + } + case 194: { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + default: + return undefined; + } + } + case 283: + return getNameOfJSDocTypedef(declaration); + case 243: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; } } - else if (declaration.kind === 283) { - return getNameOfJSDocTypedef(declaration); - } - else { - return declaration.name; - } + return declaration.name; } ts.getNameOfDeclaration = getNameOfDeclaration; function getJSDocParameterTags(param) { @@ -9077,6 +9068,11 @@ var ts; var tags = getJSDocTags(node); return ts.find(tags, function (doc) { return doc.kind === kind; }); } + function getAllJSDocTagsOfKind(node, kind) { + var tags = getJSDocTags(node); + return ts.filter(tags, function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); (function (ts) { function isNumericLiteral(node) { @@ -10311,6 +10307,14 @@ var ts; return node.kind >= 276 && node.kind <= 285; } ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 154; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 153; + } + ts.isGetAccessor = isGetAccessor; function hasJSDocNodes(node) { return !!node.jsDoc && node.jsDoc.length > 0; } @@ -16504,6 +16508,7 @@ var ts; if (tagName) { switch (tagName.escapedText) { case "augments": + case "extends": tag = parseAugmentsTag(atToken, tagName); break; case "class": @@ -16788,7 +16793,7 @@ var ts; if (typeExpression && typeExpression.type.kind === 164) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); } @@ -17013,8 +17018,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var node = array_7[_i]; visitNode(node); } } @@ -17086,8 +17091,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } return; @@ -17334,6 +17339,9 @@ var ts; var reportedUnreachableFlow = { flags: 1 }; var subtreeTransformFlags = 0; var skipTransformFlagAggregation; + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } function bindSourceFile(f, opts) { file = f; options = opts; @@ -17404,6 +17412,9 @@ var ts; } } function getDeclarationName(node) { + if (node.kind === 243) { + return node.isExportEquals ? "export=" : "default"; + } var name = ts.getNameOfDeclaration(node); if (name) { if (ts.isAmbientModule(node)) { @@ -17433,8 +17444,6 @@ var ts; return "__index"; case 244: return "__export"; - case 243: - return node.isExportEquals ? "export=" : "default"; case 194: if (ts.getSpecialPropertyAssignmentKind(node) === 2) { return "export="; @@ -17503,9 +17512,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -18157,7 +18166,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } if (!node.statement || node.statement.kind !== 212) { addAntecedent(postStatementLabel, currentFlow); @@ -18588,7 +18597,7 @@ var ts; !ts.isIdentifierName(node) && !ts.isInAmbientContext(node)) { if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); } } } @@ -18664,7 +18673,7 @@ var ts; } function checkStrictModeNumericLiteral(node) { if (inStrictMode && node.numericLiteralFlags & 4) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } function checkStrictModePostfixUnaryExpression(node) { @@ -18908,7 +18917,7 @@ var ts; } case 284: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 272 ? 4 | 16777216 : 4; return declareSymbolAndAddToSymbolTable(propTag, flags, 0); @@ -18959,20 +18968,20 @@ var ts; } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } if (node.parent.kind !== 265) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { var parent_1 = node.parent; if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } } @@ -19007,15 +19016,12 @@ var ts; function isExportsOrModuleExportsOrAlias(node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); } function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (ts.isIdentifier(node)) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - return false; + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(node) { return isExportsOrModuleExportsOrAlias(node) || @@ -19062,13 +19068,15 @@ var ts; function bindStaticPropertyAssignment(node) { var leftSideOfAssignment = node.left; var target = leftSideOfAssignment.expression; - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); + if (ts.isIdentifier(target)) { + leftSideOfAssignment.parent = node; + target.parent = leftSideOfAssignment; + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); + } } } function lookupSymbolForName(name) { @@ -19110,7 +19118,7 @@ var ts; if (node.name) { node.name.parent = node; } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); } symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); prototypeSymbol.parent = symbol; @@ -19290,6 +19298,9 @@ var ts; } if (expression.kind === 91) { transformFlags |= 67108864; + if (subtreeFlags & 16384) { + transformFlags |= 32768; + } } node.transformFlags = transformFlags | 536870912; return transformFlags & ~537396545; @@ -20241,6 +20252,23 @@ var ts; return tryFindAmbientModule(moduleName, false); }, getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getBooleanType: function () { return booleanType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, isArrayLikeType: isArrayLikeType, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, @@ -20286,6 +20314,7 @@ var ts; anyFunctionType.flags |= 8388608; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var markerSuperType = createType(16384); var markerSubType = createType(16384); markerSubType.constraint = markerSuperType; @@ -20474,6 +20503,12 @@ var ts; CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; })(CheckMode || (CheckMode = {})); + var CallbackCheck; + (function (CallbackCheck) { + CallbackCheck[CallbackCheck["None"] = 0] = "None"; + CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; + CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; + })(CallbackCheck || (CallbackCheck = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); @@ -20793,6 +20828,7 @@ var ts; var originalLocation = location; var result; var lastLocation; + var lastNonBlockLocation; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; @@ -20942,10 +20978,13 @@ var ts; } break; } + if (location.kind !== 207) { + lastNonBlockLocation = location; + } lastLocation = location; location = location.parent; } - if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; } if (!result) { @@ -23376,10 +23415,10 @@ var ts; if (parentType === unknownType) { return unknownType; } - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { return parentType; } var type; @@ -23403,9 +23442,6 @@ var ts; if (isComputedNonLiteralName(name)) { return anyType; } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } var text = ts.getTextOfPropertyName(name); var declaredType = getTypeOfPropertyOfType(parentType, text); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || @@ -24952,18 +24988,35 @@ var ts; function getApparentTypeOfIntersectionType(type) { return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); } - function getDefaultFromTypeParameter(typeParameter) { + function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; } else { + typeParameter.default = resolvingDefaultType; var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + typeParameter.default = defaultType; + } } } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + else if (typeParameter.default === resolvingDefaultType) { + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } + function getDefaultFromTypeParameter(typeParameter) { + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } function getApparentType(type) { var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; @@ -25099,7 +25152,7 @@ var ts; return getIndexTypeOfStructuredType(getApparentType(type), kind); } function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { + if (isObjectTypeWithInferableIndex(type)) { var propTypes = []; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; @@ -25196,7 +25249,7 @@ var ts; var minTypeArgumentCount = 0; if (typeParameters) { for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { + if (!hasTypeParameterDefault(typeParameters[i])) { minTypeArgumentCount = i + 1; } } @@ -26394,7 +26447,7 @@ var ts; var symbol = getAliasSymbolForTypeNode(node); return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } - function getSpreadType(left, right) { + function getSpreadType(left, right, symbol, propagatedFlags) { if (left.flags & 1 || right.flags & 1) { return anyType; } @@ -26405,10 +26458,10 @@ var ts; return left; } if (left.flags & 65536) { - return mapType(left, function (t) { return getSpreadType(t, right); }); + return mapType(left, function (t) { return getSpreadType(t, right, symbol, propagatedFlags); }); } if (right.flags & 65536) { - return mapType(right, function (t) { return getSpreadType(left, t); }); + return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } if (right.flags & 16777216) { return nonPrimitiveType; @@ -26463,7 +26516,12 @@ var ts; members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); } } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var spread = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; + spread.symbol = symbol; + return spread; } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { @@ -26746,7 +26804,7 @@ var ts; var declaration_1 = symbol.declarations[0]; var outerTypeParameters = getOuterTypeParameters(declaration_1, true) || ts.emptyArray; typeParameters = symbol.flags & 2048 && !target.aliasTypeArguments ? - ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : outerTypeParameters; links.typeParameters = typeParameters; if (typeParameters.length) { @@ -26768,13 +26826,24 @@ var ts; } return type; } - function isTypeParameterReferencedWithin(tp, node) { - return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); - function checkThis(node) { - return node.kind === 169 || ts.forEachChild(node, checkThis); + function isTypeParameterPossiblyReferenced(tp, node) { + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_1 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 207 ? "quit" : n === container_1; })) { + return ts.forEachChild(node, containsReference); + } } - function checkIdentifier(node) { - return node.kind === 71 && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + return true; + function containsReference(node) { + switch (node.kind) { + case 169: + return tp.isThisType; + case 71: + return !tp.isThisType && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp; + case 162: + return true; + } + return ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -26940,9 +27009,9 @@ var ts; return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, false, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; + return compareSignaturesRelated(source, target, 0, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; } - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { if (source === target) { return -1; } @@ -26954,7 +27023,7 @@ var ts; source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } var kind = target.declaration ? target.declaration.kind : 0; - var strictVariance = strictFunctionTypes && kind !== 151 && + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 151 && kind !== 150 && kind !== 152; var result = -1; var sourceThisType = getThisTypeOfSignature(source); @@ -26980,13 +27049,13 @@ var ts; for (var i = 0; i < checkCount; i++) { var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && (getFalsyFlags(sourceType) & 6144) === (getFalsyFlags(targetType) & 6144); var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, true, false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && !strictVariance && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 : 1, false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.symbolName(sourceParams[i < sourceMax ? i : sourceMax]), ts.symbolName(targetParams[i < targetMax ? i : targetMax])); @@ -27013,7 +27082,7 @@ var ts; } } else { - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, false) || + result &= callbackCheck === 1 && compareTypes(targetReturnType, sourceReturnType, false) || compareTypes(sourceReturnType, targetReturnType, reportErrors); } } @@ -27377,6 +27446,12 @@ var ts; (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } + if (target.flags & 65536) { + var discriminantType = findMatchingDiscriminantType(source, target); + if (discriminantType) { + return hasExcessProperties(source, discriminantType, reportErrors); + } + } var _loop_4 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -27447,22 +27522,25 @@ var ts; return 0; } function findMatchingDiscriminantType(source, target) { + var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.escapedName)) { - 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)) { - return type; + var sourceProperty = findSingleDiscriminantProperty(sourceProperties, target); + if (sourceProperty) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var type = _a[_i]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); + if (targetType && isRelatedTo(sourceType, targetType)) { + if (match) { + return undefined; } + match = type; } } } } + return match; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1; @@ -27847,8 +27925,8 @@ var ts; return 0; } var result = -1; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); if (!targetProp) { return 0; @@ -27919,7 +27997,7 @@ var ts; return result; } function signatureRelatedTo(source, target, erase, reportErrors) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, false, false, reportErrors, reportError, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0, false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -27977,7 +28055,7 @@ var ts; if (isGenericMappedType(source)) { return kind === 0 && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); } - if (isObjectLiteralType(source)) { + if (isObjectTypeWithInferableIndex(source)) { var related = -1; if (kind === 0) { var sourceNumberInfo = getIndexInfoOfType(source, 1); @@ -28364,8 +28442,8 @@ var ts; function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; } - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 | 2048)) !== 0 && + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 | 2048 | 512)) !== 0 && getSignaturesOfType(type, 0).length === 0 && getSignaturesOfType(type, 1).length === 0; } @@ -29072,6 +29150,19 @@ var ts; } return false; } + function findSingleDiscriminantProperty(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + return undefined; + } + result = sourceProperty; + } + } + return result; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -31133,7 +31224,7 @@ var ts; checkExternalEmitHelpers(memberDecl, 2); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -31145,7 +31236,7 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return unknownType; } - spread = getSpreadType(spread, type); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags); offset = i + 1; continue; } @@ -31180,13 +31271,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768) { - spread.flags |= propagatedFlags; - spread.flags |= 1048576; - spread.objectFlags |= 128; - spread.symbol = node.symbol; + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); } return spread; } @@ -31231,7 +31316,7 @@ var ts; return getJsxGlobalElementType() || anyType; } function isUnhyphenatedJsxName(name) { - return name.indexOf("-") < 0; + return !ts.stringContains(name, "-"); } function isJsxIntrinsicIdentifier(tagName) { switch (tagName.kind) { @@ -31277,7 +31362,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 255); if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, 0); attributesArray = []; attributesTable = ts.createSymbolTable(); } @@ -31286,7 +31371,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 0); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -31296,7 +31381,7 @@ var ts; if (!hasSpreadAnyType) { if (spread !== emptyObjectType) { if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, 0); } attributesArray = getPropertiesOfType(spread); } @@ -32337,29 +32422,27 @@ var ts; } return getInferredTypes(context); } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJavaScriptFile(signature.declaration); var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } + 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 && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + 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; } } - return typeArgumentsAreAssignable; + return typeArgumentTypes; } function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { var callIsIncomplete = node.attributes.end === node.end; @@ -32636,8 +32719,7 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - var typeArguments_1 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, fallbackError); + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -32679,14 +32761,14 @@ var ts; var candidate = candidates[bestIndex]; var typeParameters = candidate.typeParameters; if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_2 = node.typeArguments.map(getTypeOfNode); - while (typeArguments_2.length > typeParameters.length) { - typeArguments_2.pop(); + var typeArguments_1 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_1.length > typeParameters.length) { + typeArguments_1.pop(); } - while (typeArguments_2.length < typeParameters.length) { - typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + while (typeArguments_1.length < typeParameters.length) { + typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); } - var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + var instantiated = createSignatureInstantiation(candidate, typeArguments_1); candidates[bestIndex] = instantiated; return instantiated; } @@ -32721,10 +32803,12 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); - if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { + var typeArgumentResult = checkTypeArguments(candidate, typeArguments, false); + if (typeArgumentResult) { + typeArgumentTypes = typeArgumentResult; + } + else { candidateForTypeArgumentError = originalCandidate; break; } @@ -32732,6 +32816,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { @@ -32948,6 +33033,11 @@ var ts; if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; @@ -32958,6 +33048,13 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); } + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getEffectiveArgumentCount(decorator, undefined, signature); + }); + } function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { ts.Debug.assert(!(elementType.flags & 65536)); return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); @@ -34399,6 +34496,9 @@ var ts; if (!hasNonCircularBaseConstraint(typeParameter)) { error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } var constraintType = getConstraintOfTypeParameter(typeParameter); var defaultType = getDefaultFromTypeParameter(typeParameter); if (constraintType && defaultType) { @@ -34413,7 +34513,6 @@ var ts; checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92)) { - func = ts.getContainingFunction(node); if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } @@ -35528,17 +35627,22 @@ var ts; } } function checkJSDocAugmentsTag(node) { - var cls = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(cls) && !ts.isClassExpression(cls)) { - error(cls, ts.Diagnostics.JSDoc_augments_is_not_attached_to_a_class_declaration); + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } + var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 277); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } var name = getIdentifierFromEntityNameExpression(node.class.expression); - var extend = ts.getClassExtendsHeritageClauseElement(cls); + var extend = ts.getClassExtendsHeritageClauseElement(classLike); if (extend) { var className = getIdentifierFromEntityNameExpression(extend.expression); if (className && name.escapedText !== className.escapedText) { - error(name, ts.Diagnostics.JSDoc_augments_0_does_not_match_the_extends_1_clause, ts.idText(name), ts.idText(className)); + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); } } } @@ -35763,7 +35867,7 @@ var ts; } } function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -39875,6 +39979,9 @@ var ts; } ts.createNodeArray = createNodeArray; function getSynthesizedClone(node) { + if (node === undefined) { + return undefined; + } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; setOriginalNode(clone, node); @@ -42054,6 +42161,12 @@ var ts; return node; } ts.setEmitFlags = setEmitFlags; + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; function getSourceMapRange(node) { var emitNode = node.emitNode; return (emitNode && emitNode.sourceMapRange) || node; @@ -44317,6 +44430,14 @@ var ts; } return values; } + function isSimpleCopiableExpression(expression) { + return expression.kind === 9 || + expression.kind === 8 || + expression.kind === 13 || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; })(ts || (ts = {})); var ts; (function (ts) { @@ -44660,7 +44781,7 @@ var ts; ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; - ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; + ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; @@ -44671,6 +44792,7 @@ var ts; var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = typeof compilerOptions.strictNullChecks === "undefined" ? compilerOptions.strict : compilerOptions.strictNullChecks; var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); var previousOnEmitNode = context.onEmitNode; @@ -44943,7 +45065,8 @@ var ts; var facts = 0; if (ts.some(staticProperties)) facts |= 1; - if (ts.getClassExtendsHeritageClauseElement(node)) + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95) facts |= 64; if (shouldEmitDecorateCallForClass(node)) facts |= 2; @@ -45068,16 +45191,16 @@ var ts; } return classExpression; } - function transformClassMembers(node, hasExtendsClause) { + function transformClassMembers(node, isDerivedClass) { var members = []; - var constructor = transformConstructor(node, hasExtendsClause); + var constructor = transformConstructor(node, isDerivedClass); if (constructor) { members.push(constructor); } ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); return ts.setTextRange(ts.createNodeArray(members), node.members); } - function transformConstructor(node, hasExtendsClause) { + function transformConstructor(node, isDerivedClass) { var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); var hasParameterPropertyAssignments = node.transformFlags & 262144; var constructor = ts.getFirstConstructorWithBody(node); @@ -45085,14 +45208,14 @@ var ts; return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause); + var body = transformConstructorBody(node, constructor, isDerivedClass); return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(undefined, undefined, parameters, body), constructor || node), constructor)); } function transformConstructorParameters(constructor) { return ts.visitParameterList(constructor && constructor.parameters, visitor, context) || []; } - function transformConstructorBody(node, constructor, hasExtendsClause) { + function transformConstructorBody(node, constructor, isDerivedClass) { var statements = []; var indexOfFirstStatement = 0; resumeLexicalEnvironment(); @@ -45101,7 +45224,7 @@ var ts; var propertyAssignments = getParametersWithPropertyAssignments(constructor); ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); } - else if (hasExtendsClause) { + else if (isDerivedClass) { statements.push(ts.createStatement(ts.createCall(ts.createSuper(), undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); } var properties = getInitializedProperties(node, false); @@ -45542,6 +45665,15 @@ var ts; var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 168) { + typeNode = typeNode.type; + } + if (typeNode.kind === 130) { + continue; + } + if (!strictNullChecks && (typeNode.kind === 95 || typeNode.kind === 139)) { + continue; + } var serializedIndividual = serializeTypeNode(typeNode); if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { return serializedIndividual; @@ -45557,7 +45689,7 @@ var ts; serializedUnion = serializedIndividual; } } - return serializedUnion; + return serializedUnion || ts.createVoidZero(); } function serializeTypeReferenceNode(node) { switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { @@ -50088,7 +50220,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { - if (ts.forEach(node.arguments, containsYield)) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, true), target = _a.target, thisArg = _a.thisArg; return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), node), node); } @@ -51334,7 +51466,7 @@ var ts; default: return transformCommonJSModule; } } - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -51550,28 +51682,65 @@ var ts; } } function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var containsLexicalThis = !!(node.transformFlags & 16384); switch (compilerOptions.module) { case ts.ModuleKind.AMD: - return transformImportCallExpressionAMD(node); + return createImportCallExpressionAMD(argument, containsLexicalThis); case ts.ModuleKind.UMD: - return transformImportCallExpressionUMD(node); + return createImportCallExpressionUMD(argument, containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return transformImportCallExpressionCommonJS(node); + return createImportCallExpressionCommonJS(argument, containsLexicalThis); } } - function transformImportCallExpressionUMD(node) { + function createImportCallExpressionUMD(arg, containsLexicalThis) { needUMDDynamicImportHelper = true; - return ts.createConditional(ts.createIdentifier("__syncRequire"), transformImportCallExpressionCommonJS(node), transformImportCallExpressionAMD(node)); + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536); + return ts.createConditional(ts.createIdentifier("__syncRequire"), createImportCallExpressionCommonJS(arg, containsLexicalThis), createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(ts.createIdentifier("__syncRequire"), createImportCallExpressionCommonJS(temp, containsLexicalThis), createImportCallExpressionAMD(temp, containsLexicalThis))); + } } - function transformImportCallExpressionAMD(node) { + function createImportCallExpressionAMD(arg, containsLexicalThis) { var resolve = ts.createUniqueName("resolve"); var reject = ts.createUniqueName("reject"); - return ts.createNew(ts.createIdentifier("Promise"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, resolve), - ts.createParameter(undefined, undefined, undefined, reject)], undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + var parameters = [ + ts.createParameter(undefined, undefined, undefined, resolve), + ts.createParameter(undefined, undefined, undefined, reject) + ]; + var body = ts.createBlock([ + ts.createStatement(ts.createCall(ts.createIdentifier("require"), undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2) { + func = ts.createArrowFunction(undefined, undefined, parameters, undefined, undefined, body); + } + else { + func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, parameters, undefined, body); + if (containsLexicalThis) { + ts.setEmitFlags(func, 8); + } + } + return ts.createNew(ts.createIdentifier("Promise"), undefined, [func]); } - function transformImportCallExpressionCommonJS(node) { - return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []), "then"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, undefined, undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), undefined, node.arguments))]))]); + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []); + var requireCall = ts.createCall(ts.createIdentifier("require"), undefined, arg ? [arg] : []); + var func; + if (languageVersion >= 2) { + func = ts.createArrowFunction(undefined, undefined, [], undefined, undefined, requireCall); + } + else { + func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [], undefined, ts.createBlock([ts.createReturn(requireCall)])); + if (containsLexicalThis) { + ts.setEmitFlags(func, 8); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), undefined, [func]); } function visitImportDeclaration(node) { var statements; @@ -51674,10 +51843,10 @@ var ts; var original = node.original; if (original && hasAssociatedEndOfDeclarationMarker(original)) { var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, node, true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), node, true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, node, true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), node, true); } return ts.singleOrMany(statements); } @@ -52702,7 +52871,7 @@ var ts; } } function visitImportCallExpression(node) { - return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), undefined, node.arguments); + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); } function visitDestructuringAssignment(node) { if (hasExportedReferenceInDestructuringTarget(node.left)) { @@ -53312,7 +53481,7 @@ var ts; }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); - return comment.indexOf("@internal") >= 0; + return ts.stringContains(comment, "@internal"); } function stripInternal(node) { if (node) { @@ -56342,7 +56511,7 @@ var ts; if (ts.isNumericLiteral(expression)) { var text = getLiteralTextOfNode(expression); return !expression.numericLiteralFlags - && text.indexOf(ts.tokenToString(23)) < 0; + && !ts.stringContains(text, ts.tokenToString(23)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); @@ -57900,8 +58069,7 @@ var ts; existingInfo.version = sourceFile.version; emitHandler.onUpdateSourceFile(program, sourceFile); } - else if (program.hasInvalidatedResolution(sourceFile.path) && - emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { + else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { registerChangedFile(sourceFile.path, sourceFile.fileName); } } @@ -58665,8 +58833,7 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, - hasInvalidatedResolution: hasInvalidatedResolution + redirectTargetsSet: redirectTargetsSet }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -58963,10 +59130,15 @@ var ts; if (file.hasNoDefaultLib) { return true; } - if (defaultLibraryPath && defaultLibraryPath.length !== 0) { - return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, !host.useCaseSensitiveFileNames()); + if (!options.noLib) { + return false; + } + if (!options.lib) { + return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), !host.useCaseSensitiveFileNames()) === 0; + } + else { + return ts.forEach(options.lib, function (libFileName) { return ts.compareStrings(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName), !host.useCaseSensitiveFileNames()) === 0; }); } - return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), !host.useCaseSensitiveFileNames()) === 0; } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); @@ -63035,6 +63207,49 @@ var ts; return position; } ts.getSourceFileImportLocation = getSourceFileImportLocation; + function getSynthesizedDeepClone(node) { + if (node === undefined) { + return undefined; + } + var visited = ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); + if (visited === node) { + var clone_7 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_7)) { + clone_7.textSourceNode = node; + } + else if (ts.isNumericLiteral(clone_7)) { + clone_7.numericLiteralFlags = node.numericLiteralFlags; + } + clone_7.pos = node.pos; + clone_7.end = node.end; + return clone_7; + } + visited.parent = undefined; + return visited; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function suppressLeadingAndTrailingTrivia(node) { + ts.Debug.assert(node !== undefined); + suppressLeading(node); + suppressTrailing(node); + function suppressLeading(node) { + ts.addEmitFlags(node, 512); + var firstChild = ts.forEachChild(node, function (child) { return child; }); + firstChild && suppressLeading(firstChild); + } + function suppressTrailing(node) { + ts.addEmitFlags(node, 1024); + var lastChild = undefined; + ts.forEachChild(node, function (child) { return (lastChild = child, undefined); }, function (children) { + if (children.length) { + lastChild = ts.last(children); + } + return undefined; + }); + lastChild && suppressTrailing(lastChild); + } + } + ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; })(ts || (ts = {})); var ts; (function (ts) { @@ -64404,7 +64619,7 @@ var ts; var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = fragment.indexOf(ts.directorySeparator) !== -1; + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); @@ -64430,7 +64645,7 @@ var ts; return undefined; } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { - var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; + var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); var nonRelativeModuleNames = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); @@ -65472,6 +65687,10 @@ var ts; if (ts.isClassLike(location)) { return location; } + if (isFromClassElementDeclaration(location) && + location.parent.name === location) { + return location.parent.parent; + } break; default: if (isFromClassElementDeclaration(contextToken) && @@ -66933,9 +67152,6 @@ var ts; return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { - if (ts.isExportAssignment(decl)) { - return ts.isIdentifier(decl.expression) ? decl.expression.escapedText : undefined; - } var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 && name.escapedText; }); @@ -67314,7 +67530,7 @@ var ts; }; State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(this.checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { @@ -71141,13 +71357,19 @@ var ts; } if (symbolFlags & 2097152) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 236) { - displayParts.push(ts.keywordPart(84)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129)); - } - else { - displayParts.push(ts.keywordPart(91)); + switch (symbol.declarations[0].kind) { + case 236: + displayParts.push(ts.keywordPart(84)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(129)); + break; + case 243: + displayParts.push(ts.keywordPart(84)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 : 79)); + break; + default: + displayParts.push(ts.keywordPart(91)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -74482,6 +74704,28 @@ var ts; ts.getRefactorContextLength = getRefactorContextLength; })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); + var decorator = ts.getAncestor(token, 147); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, undefined, undefined); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), + changes: changeTracker.getChanges() + }]; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -74628,7 +74872,7 @@ var ts; var className = classDeclaration.name.getText(); var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); + staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var initializeStaticAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), changes: staticInitializationChangeTracker.getChanges() @@ -74643,7 +74887,7 @@ var ts; } var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + propertyInitializationChangeTracker.insertNodeBefore(classDeclarationSourceFile, classConstructor.body.getLastToken(), propertyInitialization, { suffix: context.newLineCharacter }); var initializeAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), changes: propertyInitializationChangeTracker.getChanges() @@ -75175,9 +75419,6 @@ var ts; this.symbolIdToActionMap = []; } ImportCodeActionMap.prototype.addAction = function (symbolId, newAction) { - if (!newAction) { - return; - } var actions = this.symbolIdToActionMap[symbolId]; if (!actions) { this.symbolIdToActionMap[symbolId] = [newAction]; @@ -75195,14 +75436,14 @@ var ts; continue; } switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) { - case ModuleSpecifierComparison.Better: + case 0: if (newAction.kind === "NewImport") { return; } - case ModuleSpecifierComparison.Equal: + case 1: updatedNewImports.push(existingAction); break; - case ModuleSpecifierComparison.Worse: + case 2: continue; } } @@ -75224,25 +75465,25 @@ var ts; }; ImportCodeActionMap.prototype.compareModuleSpecifiers = function (moduleSpecifier1, moduleSpecifier2) { if (moduleSpecifier1 === moduleSpecifier2) { - return ModuleSpecifierComparison.Equal; + return 1; } if (moduleSpecifier2.indexOf(moduleSpecifier1) === 0) { - return ModuleSpecifierComparison.Better; + return 0; } if (moduleSpecifier1.indexOf(moduleSpecifier2) === 0) { - return ModuleSpecifierComparison.Worse; + return 2; } if (ts.isExternalModuleNameRelative(moduleSpecifier1) && ts.isExternalModuleNameRelative(moduleSpecifier2)) { var regex = new RegExp(ts.directorySeparator, "g"); var moduleSpecifier1LevelCount = (moduleSpecifier1.match(regex) || []).length; var moduleSpecifier2LevelCount = (moduleSpecifier2.match(regex) || []).length; return moduleSpecifier1LevelCount < moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Better + ? 0 : moduleSpecifier1LevelCount === moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Equal - : ModuleSpecifierComparison.Worse; + ? 1 + : 2; } - return ModuleSpecifierComparison.Equal; + return 1; }; return ImportCodeActionMap; }()); @@ -75893,6 +76134,548 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + ], + getCodeActions: getActionsForAddExplicitTypeAnnotation + }); + function getActionsForAddExplicitTypeAnnotation(_a) { + var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + var token = ts.getTokenAtPosition(sourceFile, start, false); + var writer; + if (ts.isInJavaScriptFile(token)) { + return undefined; + } + switch (token.kind) { + case 71: + case 24: + case 114: + case 112: + case 113: + case 131: + break; + default: + return undefined; + } + var containingFunction = ts.getContainingFunction(token); + var checker = program.getTypeChecker(); + switch (errorCode) { + 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: + return getCodeActionForVariableDeclaration(token.parent); + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: + return getCodeActionForVariableUsage(token); + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessor(containingFunction)) { + return getCodeActionForSetAccessor(containingFunction); + } + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + return getCodeActionForParameters(token.parent); + 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: + return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined; + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined; + } + return undefined; + function getCodeActionForVariableDeclaration(declaration) { + if (!ts.isIdentifier(declaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(declaration.name); + var typeString = type && typeToString(type, declaration); + if (!typeString) { + return undefined; + } + return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), ": " + typeString); + } + function getCodeActionForVariableUsage(token) { + var symbol = checker.getSymbolAtLocation(token); + return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration); + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 228: + case 151: + case 152: + return true; + case 186: + return !!declaration.name; + } + return false; + } + function getCodeActionForParameters(parameterDeclaration) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return undefined; + } + var types = inferTypeForParametersFromUsage(containingFunction) || + ts.map(containingFunction.parameters, function (p) { return ts.isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name); }); + if (!types) { + return undefined; + } + var textChanges = ts.zipWith(containingFunction.parameters, types, function (parameter, type) { + if (type && !parameter.type && !parameter.initializer) { + var typeString = typeToString(type, containingFunction); + return typeString ? { + span: { start: parameter.end, length: 0 }, + newText: ": " + typeString + } : undefined; + } + }).filter(function (c) { return !!c; }); + return textChanges.length ? [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: textChanges + }] + }] : undefined; + } + function getCodeActionForSetAccessor(setAccessorDeclaration) { + var setAccessorParameter = setAccessorDeclaration.parameters[0]; + if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) || + inferTypeForVariableFromUsage(setAccessorParameter.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), ": " + typeString); + } + function getCodeActionForGetAccessor(getAccessorDeclaration) { + if (!ts.isIdentifier(getAccessorDeclaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + var closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, 20); + return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), ": " + typeString); + } + function createCodeActions(name, start, typeString) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_type_of_0_from_usage), [name]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: start, length: 0 }, + newText: typeString + }] + }] + }]; + } + function getReferences(token) { + var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), token.getSourceFile(), token.getStart()); + ts.Debug.assert(!!references, "Found no references!"); + ts.Debug.assert(references.length === 1, "Found more references than expected"); + return ts.map(references[0].references, function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, false); }); + } + function inferTypeForVariableFromUsage(token) { + return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken); + } + function inferTypeForParametersFromUsage(containingFunction) { + switch (containingFunction.kind) { + case 152: + case 186: + case 228: + case 151: + var isConstructor = containingFunction.kind === 152; + var searchToken = isConstructor ? + getFirstChildOfKind(containingFunction, sourceFile, 123) : + containingFunction.name; + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken); + } + } + } + function getTypeAccessiblityWriter() { + if (!writer) { + var str_1 = ""; + var typeIsAccessible_1 = true; + var writeText = function (text) { return str_1 += text; }; + writer = { + string: function () { return typeIsAccessible_1 ? str_1 : undefined; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + writeLine: function () { return str_1 += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { str_1 = ""; typeIsAccessible_1 = true; }, + trackSymbol: function (symbol, declaration, meaning) { + if (checker.isSymbolAccessible(symbol, declaration, meaning, false).accessibility !== 0) { + typeIsAccessible_1 = false; + } + }, + reportInaccessibleThisError: function () { typeIsAccessible_1 = false; }, + reportPrivateInBaseOfClassExpression: function () { typeIsAccessible_1 = false; }, + }; + } + writer.clear(); + return writer; + } + function typeToString(type, enclosingDeclaration) { + var writer = getTypeAccessiblityWriter(); + checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); + return writer.string(); + } + function getFirstChildOfKind(node, sourcefile, kind) { + for (var _i = 0, _a = node.getChildren(sourcefile); _i < _a.length; _i++) { + var child = _a[_i]; + if (child.kind === kind) + return child; + } + return undefined; + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypeFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return getTypeFromUsageContext(usageContext, checker); + } + InferFromReference.inferTypeFromReferences = inferTypeFromReferences; + function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { + if (declaration.parameters) { + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var isConstructor = declaration.kind === 152; + var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; + if (callContexts) { + var paramTypes = []; + for (var parameterIndex = 0; parameterIndex < declaration.parameters.length; parameterIndex++) { + var types = []; + var isRestParameter_1 = ts.isRestParameter(declaration.parameters[parameterIndex]); + for (var _a = 0, callContexts_1 = callContexts; _a < callContexts_1.length; _a++) { + var callContext = callContexts_1[_a]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter_1) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, true)); + paramTypes[parameterIndex] = isRestParameter_1 ? checker.createArrayType(type) : type; + } + } + return paramTypes; + } + } + return undefined; + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 193: + usageContext.isNumber = true; + break; + case 192: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 194: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 257: + case 258: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 181: + case 182: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 179: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 180: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isPartOfExpression(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 43: + case 44: + case 38: + case 52: + usageContext.isNumber = true; + break; + case 37: + usageContext.isNumberOrString = true; + break; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + case 40: + case 39: + case 41: + case 42: + case 45: + case 46: + case 47: + case 48: + case 49: + case 50: + case 60: + case 62: + case 61: + case 63: + case 64: + case 68: + case 69: + case 70: + case 65: + case 67: + case 66: + case 38: + case 27: + case 30: + case 29: + case 31: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 272) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 59: + case 37: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 272) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 84) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 262178) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + case 58: + case 32: + case 34: + case 35: + case 33: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 92: + if (node === parent.left) { + usageContext.isString = true; + } + break; + case 54: + if (node === parent.left && + (node.parent.parent.kind === 226 || ts.isAssignmentExpression(node.parent.parent, true))) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 53: + case 26: + case 93: + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 181) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 84) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function getTypeFromUsageContext(usageContext, checker) { + if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { + return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); + } + else if (usageContext.isNumber) { + return checker.getNumberType(); + } + else if (usageContext.isString) { + return checker.getStringType(); + } + else if (usageContext.candidateTypes) { + return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), true)); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, false, checker); + var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + return checker.createPromiseType(types.length ? checker.getUnionType(types, true) : checker.getAnyType()); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { + return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, false, checker)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + var members_4 = 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, name); + symbol.type = getTypeFromUsageContext(context, checker); + members_4.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.numberIndexContext) { + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), false); + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), false); + } + return checker.createAnonymousType(undefined, members_4, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + return undefined; + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, true)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = getTypeFromUsageContext(callContext.returnType, checker); + return checker.createSignature(undefined, undefined, undefined, parameters, returnType, undefined, callContext.argumentTypes.length, false, false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1) && !(type.flags & 8192)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return usageContext && usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var refactor; (function (refactor) { @@ -76034,7 +76817,8 @@ var ts; switch (assignmentBinaryExpression.right.kind) { case 186: { var functionExpression = assignmentBinaryExpression.right; - var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120)); + var method = ts.createMethod(undefined, fullModifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); copyComments(assignmentBinaryExpression, method); return method; } @@ -76049,7 +76833,8 @@ var ts; var expression = arrowFunctionBody; bodyBlock = ts.createBlock([ts.createReturn(expression)]); } - var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120)); + var method = ts.createMethod(undefined, fullModifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); copyComments(assignmentBinaryExpression, method); return method; } @@ -76088,7 +76873,8 @@ var ts; if (initializer.body) { memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body)); } - var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + var modifiers = getModifierKindFromSource(precedingNode, 84); + var cls = ts.createClassDeclaration(undefined, modifiers, node.name, undefined, undefined, memberElements); return cls; } function createClassFromFunctionDeclaration(node) { @@ -76096,9 +76882,13 @@ var ts; if (node.body) { memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); } - var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + var modifiers = getModifierKindFromSource(node, 84); + var cls = ts.createClassDeclaration(undefined, modifiers, node.name, undefined, undefined, memberElements); return cls; } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } } })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); @@ -76211,7 +77001,7 @@ var ts; Messages.FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); Messages.CannotExtractIdentifier = createMessage("Select more than a single identifier."); Messages.CannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); - Messages.CannotCombineWritesAndReturns = createMessage("Cannot combine writes and returns"); + Messages.CannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); Messages.CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); Messages.CannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); @@ -76370,7 +77160,7 @@ var ts; permittedJumps = 0; break; case 207: - if (node.parent && node.parent.kind === 224 && node.finallyBlock === node) { + if (node.parent && node.parent.kind === 224 && node.parent.finallyBlock === node) { permittedJumps = 4; } break; @@ -76452,7 +77242,10 @@ var ts; if (range.facts & RangeFacts.UsesThis) { var containingClass = ts.getContainingClass(current); if (containingClass) { - return [containingClass]; + var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration); + return containingFunction + ? [containingFunction, containingClass] + : [containingClass]; } } var start = current; @@ -76471,14 +77264,15 @@ var ts; return scopes; } function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope; + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); context.cancellationToken.throwIfCancellationRequested(); - return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); } function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope; + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); context.cancellationToken.throwIfCancellationRequested(); var expression = ts.isExpression(target) ? target @@ -76589,12 +77383,12 @@ var ts; })(SpecialScope || (SpecialScope = {})); function getUniqueName(baseName, fileText) { var nameText = baseName; - for (var i = 1; fileText.indexOf(nameText) !== -1; i++) { + for (var i = 1; ts.stringContains(fileText, nameText); i++) { nameText = baseName + "_" + i; } return nameText; } - function extractFunctionInScope(node, scope, _a, range, context) { + function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); var file = scope.getSourceFile(); @@ -76629,9 +77423,10 @@ var ts; : undefined; if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType); + returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); } - var _b = transformFunctionBody(node, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + ts.suppressLeadingAndTrailingTrivia(body); var newFunction; if (ts.isClassLike(scope)) { var modifiers = isJS ? [] : [ts.createToken(112)]; @@ -76653,7 +77448,10 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); } else { - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { + prefix: ts.isLineBreak(file.text.charCodeAt(scope.getLastToken().pos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter, + suffix: context.newLineCharacter + }); } var newNodes = []; var called = getCalledExpression(scope, range, functionNameText); @@ -76664,27 +77462,60 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { call = ts.createAwait(call); } - if (writes) { - if (returnValueProperty) { - newNodes.push(ts.createVariableStatement(undefined, [ts.createVariableDeclaration(returnValueProperty, ts.createKeywordTypeNode(119))])); + if (exposedVariableDeclarations.length && !writes) { + ts.Debug.assert(!returnValueProperty); + ts.Debug.assert(!(range.facts & RangeFacts.HasReturn)); + if (exposedVariableDeclarations.length === 1) { + var variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), ts.getSynthesizedDeepClone(variableDeclaration.type), call)], variableDeclaration.parent.flags))); } - var assignments = getPropertyAssignmentsForWrites(writes); + else { + var bindingElements = []; + var typeElements = []; + var commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + var sawExplicitType = false; + for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { + var variableDeclaration = exposedVariableDeclarations_1[_i]; + bindingElements.push(ts.createBindingElement(undefined, undefined, ts.getSynthesizedDeepClone(variableDeclaration.name))); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + typeElements.push(ts.createPropertySignature(undefined, variableDeclaration.symbol.name, undefined, variableType, undefined)); + sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined; + if (typeLiteral) { + ts.setEmitFlags(typeLiteral, 1); + } + newNodes.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), typeLiteral, call)], commonNodeFlags))); + } + } + else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) { + var variableDeclaration = exposedVariableDeclarations_2[_c]; + var flags = variableDeclaration.parent.flags; + if (flags & 2) { + flags = (flags & ~2) | 1; + } + newNodes.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags))); + } + } + if (returnValueProperty) { + newNodes.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1))); + } + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (returnValueProperty) { assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); } if (assignments.length === 1) { - if (returnValueProperty) { - newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); - } - else { - newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58, call))); - if (range.facts & RangeFacts.HasReturn) { - newNodes.push(ts.createReturn()); - } + ts.Debug.assert(!returnValueProperty); + newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); } } else { - newNodes.push(ts.createStatement(ts.createBinary(ts.createObjectLiteral(assignments), 58, call))); + newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call))); if (returnValueProperty) { newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); } @@ -76701,20 +77532,28 @@ var ts; newNodes.push(call); } } - if (isReadonlyArray(range.range)) { - changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes, { - nodeSeparator: context.newLineCharacter, - suffix: context.newLineCharacter - }); - } - else { - changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); - } + var replacementRange = isReadonlyArray(range.range) + ? { pos: ts.first(range.range).getStart(), end: ts.last(range.range).end } + : { pos: range.range.getStart(), end: range.range.end }; + changeTracker.replaceRangeWithNodes(context.file, replacementRange, newNodes, { nodeSeparator: context.newLineCharacter }); var edits = changeTracker.getChanges(); var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; var renameFilename = renameRange.getSourceFile().fileName; var renameLocation = getRenameLocation(edits, renameFilename, functionNameText, false); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === undefined) { + return undefined; + } + var clone = ts.getSynthesizedDeepClone(typeNode); + var withoutParens = clone; + while (ts.isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 139; }) + ? clone + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(139)]); + } } function extractConstantInScope(node, scope, _a, rangeFacts, context) { var substitutions = _a.substitutions; @@ -76724,8 +77563,9 @@ var ts; var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS ? undefined - : checker.typeToTypeNode(checker.getContextualType(node)); + : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); var initializer = transformConstantInitializer(node, substitutions); + ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); if (ts.isClassLike(scope)) { ts.Debug.assert(!isJS); @@ -76742,7 +77582,7 @@ var ts; var maxInsertionPos = node.pos; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, { suffix: context.newLineCharacter + context.newLineCharacter }); - changeTracker.replaceNodeWithNodes(context.file, node, [localReference], { nodeSeparator: context.newLineCharacter }); + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); } else { var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); @@ -76867,17 +77707,18 @@ var ts; return functionReference; } } - function transformFunctionBody(body, writes, substitutions, hasReturn) { - if (ts.isBlock(body) && !writes && substitutions.size === 0) { + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) { + var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; + if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { return { body: ts.createBlock(body.statements, true), returnValueProperty: undefined }; } var returnValueProperty; var ignoreReturns = false; var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); - if (writes || substitutions.size) { + if (hasWritesOrVariableDeclarations || substitutions.size) { var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); - if (writes && !hasReturn && ts.isStatement(body)) { - var assignments = getPropertyAssignmentsForWrites(writes); + if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (assignments.length === 1) { rewrittenStatements.push(ts.createReturn(assignments[0].name)); } @@ -76891,8 +77732,8 @@ var ts; return { body: ts.createBlock(statements, true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 219 && writes) { - var assignments = getPropertyAssignmentsForWrites(writes); + if (!ignoreReturns && node.kind === 219 && hasWritesOrVariableDeclarations) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { returnValueProperty = "__return"; @@ -76910,7 +77751,7 @@ var ts; var oldIgnoreReturns = ignoreReturns; ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node); var substitution = substitutions.get(ts.getNodeId(node).toString()); - var result = substitution ? substitution() : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); ignoreReturns = oldIgnoreReturns; return result; } @@ -76922,7 +77763,7 @@ var ts; : initializer; function visitor(node) { var substitution = substitutions.get(ts.getNodeId(node).toString()); - return substitution ? substitution() : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); } } function getStatementsOrClassElements(scope) { @@ -76953,8 +77794,8 @@ var ts; ts.Debug.assert(members.length > 0); var prevMember = undefined; var allProperties = true; - for (var _i = 0, members_4 = members; _i < members_4.length; _i++) { - var member = members_4[_i]; + for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { + var member = members_5[_i]; if (member.pos > maxPos) { return prevMember || members[0]; } @@ -76996,8 +77837,14 @@ var ts; } } } - function getPropertyAssignmentsForWrites(writes) { - return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); + var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + return variableAssignments === undefined + ? writeAssignments + : writeAssignments === undefined + ? variableAssignments + : variableAssignments.concat(writeAssignments); } function isReadonlyArray(v) { return ts.isArray(v); @@ -77019,6 +77866,9 @@ var ts; var functionErrorsPerScope = []; var constantErrorsPerScope = []; var visibleDeclarationsInExtractedRange = []; + var exposedVariableSymbolSet = ts.createMap(); + var exposedVariableDeclarations = []; + var firstExposedNonVariableDeclaration = undefined; var expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) @@ -77055,7 +77905,6 @@ var ts; } var seenUsages = ts.createMap(); var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; - var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range; var inGenericContext = isInGenericContext(unmodifiedNode); collectUsages(target); @@ -77085,6 +77934,12 @@ var ts; } ts.Debug.assert(i_1 === scopes.length); } + if (visibleDeclarationsInExtractedRange.length) { + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) + ? scopes[0] + : ts.getEnclosingBlockScopeContainer(scopes[0]); + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } var _loop_8 = function (i) { var scopeUsages = usagesPerScope[i]; if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { @@ -77103,8 +77958,9 @@ var ts; } } }); - if (hasWrite && !isReadonlyArray(targetRange.range) && ts.isExpression(targetRange.range)) { - var diag = ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns); + ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + var diag = ts.createDiagnosticForNode(targetRange.range, Messages.CannotWriteInExpression); functionErrorsPerScope[i].push(diag); constantErrorsPerScope[i].push(diag); } @@ -77113,14 +77969,16 @@ var ts; functionErrorsPerScope[i].push(diag); constantErrorsPerScope[i].push(diag); } + else if (firstExposedNonVariableDeclaration) { + var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.CannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } }; for (var i = 0; i < scopes.length; i++) { _loop_8(i); } - if (visibleDeclarationsInExtractedRange.length) { - ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); - } - return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope }; + return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function hasTypeParameters(node) { return ts.isDeclarationWithTypeParameters(node) && node.typeParameters !== undefined && @@ -77151,7 +78009,7 @@ var ts; recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { - visibleDeclarationsInExtractedRange.push(node.symbol); + visibleDeclarationsInExtractedRange.push(node); } if (ts.isAssignmentExpression(node)) { collectUsages(node.left, 2); @@ -77191,9 +78049,7 @@ var ts; } } function recordUsagebySymbol(identifier, usage, isTypeName) { - var symbol = identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier - ? checker.getShorthandAssignmentValueSymbol(identifier.parent) - : checker.getSymbolAtLocation(identifier); + var symbol = getSymbolReferencedByIdentifier(identifier); if (!symbol) { return undefined; } @@ -77260,37 +78116,45 @@ var ts; if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) { return; } - var sym = checker.getSymbolAtLocation(node); - if (sym && visibleDeclarationsInExtractedRange.some(function (d) { return d === sym; })) { - var diag = ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity); - for (var _i = 0, functionErrorsPerScope_2 = functionErrorsPerScope; _i < functionErrorsPerScope_2.length; _i++) { - var errors = functionErrorsPerScope_2[_i]; - errors.push(diag); + var sym = ts.isIdentifier(node) + ? getSymbolReferencedByIdentifier(node) + : checker.getSymbolAtLocation(node); + if (sym) { + var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; }); + if (decl) { + if (ts.isVariableDeclaration(decl)) { + var idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } + else { + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } } - for (var _a = 0, constantErrorsPerScope_2 = constantErrorsPerScope; _a < constantErrorsPerScope_2.length; _a++) { - var errors = constantErrorsPerScope_2[_a]; - errors.push(diag); - } - return true; - } - else { - ts.forEachChild(node, checkForUsedDeclarations); } + ts.forEachChild(node, checkForUsedDeclarations); + } + function getSymbolReferencedByIdentifier(identifier) { + return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); } function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { if (!symbol) { return undefined; } if (symbol.getDeclarations().some(function (d) { return d.parent === scopeDecl; })) { - return function () { return ts.createIdentifier(symbol.name); }; + return ts.createIdentifier(symbol.name); } var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode); if (prefix === undefined) { return undefined; } return isTypeNode - ? function () { return ts.createQualifiedName(prefix(), ts.createIdentifier(symbol.name)); } - : function () { return ts.createPropertyAccess(prefix(), symbol.name); }; + ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) + : ts.createPropertyAccess(prefix, symbol.name); } } function getParentNodeInSpan(node, file, span) { @@ -78674,7 +79538,7 @@ var ts; } function isNodeModulesFile(path) { var node_modulesFolderName = "/node_modules/"; - return path.indexOf(node_modulesFolderName) !== -1; + return ts.stringContains(path, node_modulesFolderName); } } function getRenameInfo(fileName, position) { @@ -80293,18 +81157,28 @@ var ts; ts.addFileWatcher = addFileWatcher; function addFileWatcherWithLogging(host, file, cb, log) { var watcherCaption = "FileWatcher:: "; - return createWatcherWithLogging(addFileWatcher, watcherCaption, log, host, file, cb); + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, false, host, file, cb); } ts.addFileWatcherWithLogging = addFileWatcherWithLogging; + function addFileWatcherWithOnlyTriggerLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, true, host, file, cb); + } + ts.addFileWatcherWithOnlyTriggerLogging = addFileWatcherWithOnlyTriggerLogging; function addFilePathWatcher(host, file, cb, path) { return host.watchFile(file, function (fileName, eventKind) { return cb(fileName, eventKind, path); }); } ts.addFilePathWatcher = addFilePathWatcher; function addFilePathWatcherWithLogging(host, file, cb, path, log) { var watcherCaption = "FileWatcher:: "; - return createWatcherWithLogging(addFileWatcher, watcherCaption, log, host, file, cb, path); + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, false, host, file, cb, path); } ts.addFilePathWatcherWithLogging = addFilePathWatcherWithLogging; + function addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, true, host, file, cb, path); + } + ts.addFilePathWatcherWithOnlyTriggerLogging = addFilePathWatcherWithOnlyTriggerLogging; function addDirectoryWatcher(host, directory, cb, flags) { var recursive = (flags & 1) !== 0; return host.watchDirectory(directory, cb, recursive); @@ -80312,12 +81186,19 @@ var ts; ts.addDirectoryWatcher = addDirectoryWatcher; function addDirectoryWatcherWithLogging(host, directory, cb, flags, log) { var watcherCaption = "DirectoryWatcher " + ((flags & 1) !== 0 ? "recursive" : "") + ":: "; - return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, host, directory, cb, flags); + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, false, host, directory, cb, flags); } ts.addDirectoryWatcherWithLogging = addDirectoryWatcherWithLogging; - function createWatcherWithLogging(addWatch, watcherCaption, log, host, file, cb, optional) { + function addDirectoryWatcherWithOnlyTriggerLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, true, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithOnlyTriggerLogging = addDirectoryWatcherWithOnlyTriggerLogging; + function createWatcherWithLogging(addWatch, watcherCaption, log, logOnlyTrigger, host, file, cb, optional) { var info = "PathInfo: " + file; - log(watcherCaption + "Added: " + info); + if (!logOnlyTrigger) { + log(watcherCaption + "Added: " + info); + } var watcher = addWatch(host, file, function (fileName, cbOptional1) { var optionalInfo = cbOptional1 !== undefined ? " " + cbOptional1 : ""; log(watcherCaption + "Trigger: " + fileName + optionalInfo + " " + info); @@ -80328,7 +81209,9 @@ var ts; }, optional); return { close: function () { - log(watcherCaption + "Close: " + info); + if (!logOnlyTrigger) { + log(watcherCaption + "Close: " + info); + } watcher.close(); } }; @@ -80363,7 +81246,7 @@ var ts; return { startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, - startCachingPerDirectoryResolution: startCachingPerDirectoryResolution, + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, @@ -80393,7 +81276,7 @@ var ts; resolvedModuleNames.clear(); resolvedTypeReferenceDirectives.clear(); allFilesHaveInvalidatedResolution = false; - ts.Debug.assert(perDirectoryResolvedModuleNames.size === 0 && perDirectoryResolvedTypeReferenceDirectives.size === 0); + clearPerDirectoryResolutions(); } function startRecordingFilesWithChangedResolutions() { filesWithChangedSetOfUnresolvedImports = []; @@ -80412,8 +81295,9 @@ var ts; filesWithInvalidatedResolutions = undefined; return function (path) { return collected && collected.has(path); }; } - function startCachingPerDirectoryResolution() { - ts.Debug.assert(perDirectoryResolvedModuleNames.size === 0 && perDirectoryResolvedTypeReferenceDirectives.size === 0); + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); } function finishCachingPerDirectoryResolution() { allFilesHaveInvalidatedResolution = false; @@ -80423,8 +81307,7 @@ var ts; watcher.watcher.close(); } }); - perDirectoryResolvedModuleNames.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); @@ -80527,14 +81410,11 @@ var ts; } var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); var dirPath = ts.getDirectoryPath(failedLookupLocationPath); - if (isNodeModulesDirectory(dirPath)) { - return { dir: dir, dirPath: dirPath }; + while (ts.stringContains(dirPath, "/node_modules/")) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); } - if (dirPath.indexOf("/node_modules/") !== -1) { - while (!isNodeModulesDirectory(dirPath)) { - dir = ts.getDirectoryPath(dir); - dirPath = ts.getDirectoryPath(dirPath); - } + if (isNodeModulesDirectory(dirPath)) { return { dir: dir, dirPath: dirPath }; } if (rootPath !== undefined) { @@ -80911,7 +81791,7 @@ var ts; } server.isScriptInfo = isScriptInfo; var Project = (function () { - function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, directoryStructureHost, rootDirectoryForResolution) { + function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { this.projectName = projectName; this.projectKind = projectKind; this.projectService = projectService; @@ -80927,6 +81807,7 @@ var ts; this.projectStructureVersion = 0; this.projectStateVersion = 0; this.hasChangedAutomaticTypeDirectiveNames = false; + this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || ""); this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); if (!this.compilerOptions) { this.compilerOptions = ts.getDefaultCompilerOptions(); @@ -80944,8 +81825,8 @@ var ts; if (host.realpath) { this.realpath = function (path) { return host.realpath(path); }; } + this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory); this.languageService = ts.createLanguageService(this, this.documentRegistry); - this.resolutionCache = ts.createResolutionCache(this, rootDirectoryForResolution); if (!languageServiceEnabled) { this.disableLanguageService(); } @@ -81025,10 +81906,10 @@ var ts; return this.cancellationToken; }; Project.prototype.getCurrentDirectory = function () { - return this.directoryStructureHost.getCurrentDirectory(); + return this.currentDirectory; }; Project.prototype.getDefaultLibFileName = function () { - var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.projectService.host.getExecutingFilePath())); + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.projectService.getExecutingFilePath())); return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilerOptions)); }; Project.prototype.useCaseSensitiveFileNames = function () { @@ -81125,10 +82006,9 @@ var ts; this.ensureBuilder(); var _a = this.builder.emitFile(this.program, scriptInfo.path), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; if (!emitSkipped) { - var projectRootPath = this.getProjectRootPath(); for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { var outputFile = outputFiles_1[_i]; - var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName)); + var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, this.currentDirectory); writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); } } @@ -81163,23 +82043,21 @@ var ts; return this.program.getSourceFileByPath(path); }; Project.prototype.close = function () { + var _this = this; if (this.program) { for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { var f = _a[_i]; - var info = this.projectService.getScriptInfo(f.fileName); - if (info) { - info.detachFromProject(this); - } + this.detachScriptInfoIfNotRoot(f.fileName); } } - if (!this.program || !this.languageServiceEnabled) { - for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { - var root = _c[_b]; - root.detachFromProject(this); - } + ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); }); + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; + root.detachFromProject(this); } this.rootFiles = undefined; this.rootFilesMap = undefined; + this.externalFiles = undefined; this.program = undefined; this.builder = undefined; this.resolutionCache.clear(); @@ -81193,6 +82071,12 @@ var ts; this.languageService.dispose(); this.languageService = undefined; }; + Project.prototype.detachScriptInfoIfNotRoot = function (uncheckedFilename) { + var info = this.projectService.getScriptInfo(uncheckedFilename); + if (info && !this.isRoot(info)) { + info.detachFromProject(this); + } + }; Project.prototype.isClosed = function () { return this.rootFiles === undefined; }; @@ -81216,7 +82100,7 @@ var ts; return ts.map(this.program.getSourceFiles(), function (sourceFile) { var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); if (!scriptInfo) { - ts.Debug.fail("scriptInfo for a file '" + sourceFile.fileName + "' is missing."); + ts.Debug.fail("scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' is missing."); } return scriptInfo; }); @@ -81361,7 +82245,6 @@ var ts; }; Project.prototype.updateGraph = function () { this.resolutionCache.startRecordingFilesWithChangedResolutions(); - this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution(); var hasChanges = this.updateGraphWorker(); var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray; for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) { @@ -81407,8 +82290,10 @@ var ts; Project.prototype.updateGraphWorker = function () { var _this = this; var oldProgram = this.program; + ts.Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); this.writeLog("Starting updateGraphWorker: Project: " + this.getProjectName()); var start = ts.timestamp(); + this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution(); this.resolutionCache.startCachingPerDirectoryResolution(); this.program = this.languageService.getProgram(); this.resolutionCache.finishCachingPerDirectoryResolution(); @@ -81565,10 +82450,10 @@ var ts; server.Project = Project; var InferredProject = (function (_super) { __extends(InferredProject, _super); - function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, rootDirectoryForResolution) { - var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, true, compilerOptions, false, projectService.host, rootDirectoryForResolution) || this; - _this.projectRootPath = projectRootPath; + function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory) { + var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, true, compilerOptions, false, projectService.host, currentDirectory) || this; _this._isJsInferredProject = false; + _this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -81611,10 +82496,6 @@ var ts; return (!this.projectRootPath && !this.projectService.useSingleInferredProject) || this.getRootScriptInfos().length === 1; }; - InferredProject.prototype.getProjectRootPath = function () { - return this.projectRootPath || - !this.projectService.useSingleInferredProject && ts.getDirectoryPath(this.getRootFiles()[0]); - }; InferredProject.prototype.close = function () { var _this = this; ts.forEach(this.getRootScriptInfos(), function (info) { return _this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); }); @@ -81670,7 +82551,7 @@ var ts; this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } - var searchPaths = [ts.combinePaths(host.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.allowLocalPluginLoads) { var local = ts.getDirectoryPath(this.canonicalConfigFilePath); this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths"); @@ -81744,14 +82625,11 @@ var ts; this.projectService.logger.info("Plugin activation failed: " + e); } }; - ConfiguredProject.prototype.getProjectRootPath = function () { - return ts.getDirectoryPath(this.getConfigFilePath()); - }; ConfiguredProject.prototype.getGlobalProjectErrors = function () { - return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }); + return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray; }; ConfiguredProject.prototype.getAllProjectErrors = function () { - return this.projectErrors; + return this.projectErrors || server.emptyArray; }; ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { this.projectErrors = projectErrors; @@ -81789,12 +82667,14 @@ var ts; } }; ConfiguredProject.prototype.close = function () { - _super.prototype.close.call(this); if (this.configFileWatcher) { this.configFileWatcher.close(); this.configFileWatcher = undefined; } this.stopWatchingWildCards(); + this.projectErrors = undefined; + this.configFileSpecs = undefined; + _super.prototype.close.call(this); }; ConfiguredProject.prototype.addOpenRef = function () { this.openRefCount++; @@ -81826,19 +82706,12 @@ var ts; var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, projectService.host, ts.getDirectoryPath(projectFilePath || ts.normalizeSlashes(externalProjectName))) || this; _this.externalProjectName = externalProjectName; _this.compileOnSaveEnabled = compileOnSaveEnabled; - _this.projectFilePath = projectFilePath; _this.excludedFiles = []; return _this; } ExternalProject.prototype.getExcludedFiles = function () { return this.excludedFiles; }; - ExternalProject.prototype.getProjectRootPath = function () { - if (this.projectFilePath) { - return ts.getDirectoryPath(this.projectFilePath); - } - return ts.getDirectoryPath(ts.normalizeSlashes(this.getProjectName())); - }; ExternalProject.prototype.getTypeAcquisition = function () { return this.typeAcquisition; }; @@ -82028,7 +82901,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.host.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); this.currentDirectory = this.host.getCurrentDirectory(); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); @@ -82049,6 +82922,11 @@ var ts; this.watchFilePath = function (host, file, cb, path, watchType, project) { return ts.addFilePathWatcherWithLogging(host, file, cb, path, _this.createWatcherLog(watchType, project)); }; this.watchDirectory = function (host, dir, cb, flags, watchType, project) { return ts.addDirectoryWatcherWithLogging(host, dir, cb, flags, _this.createWatcherLog(watchType, project)); }; } + else if (this.logger.loggingEnabled()) { + this.watchFile = function (host, file, cb, watchType, project) { return ts.addFileWatcherWithOnlyTriggerLogging(host, file, cb, _this.createWatcherLog(watchType, project)); }; + this.watchFilePath = function (host, file, cb, path, watchType, project) { return ts.addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, _this.createWatcherLog(watchType, project)); }; + this.watchDirectory = function (host, dir, cb, flags, watchType, project) { return ts.addDirectoryWatcherWithOnlyTriggerLogging(host, dir, cb, flags, _this.createWatcherLog(watchType, project)); }; + } else { this.watchFile = ts.addFileWatcher; this.watchFilePath = ts.addFilePathWatcher; @@ -82063,6 +82941,12 @@ var ts; ProjectService.prototype.toPath = function (fileName) { return ts.toPath(fileName, this.currentDirectory, this.toCanonicalFileName); }; + ProjectService.prototype.getExecutingFilePath = function () { + return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath()); + }; + ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) { + return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); + }; ProjectService.prototype.getChangedFiles_TestOnly = function () { return this.changedFiles; }; @@ -82170,8 +83054,9 @@ var ts; ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled"); var compilerOptions = convertCompilerOptions(projectCompilerOptions); compilerOptions.allowNonTsExtensions = true; - if (projectRootPath) { - this.compilerOptionsForInferredProjectsPerProjectRoot.set(projectRootPath, compilerOptions); + var canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath); + if (canonicalProjectRootPath) { + this.compilerOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, compilerOptions); } else { this.compilerOptionsForInferredProjects = compilerOptions; @@ -82179,8 +83064,8 @@ var ts; var projectsToUpdate = []; for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var project = _a[_i]; - if (projectRootPath ? - project.projectRootPath === projectRootPath : + if (canonicalProjectRootPath ? + project.projectRootPath === canonicalProjectRootPath : !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) { project.setCompilerOptions(compilerOptions); project.compileOnSaveEnabled = compilerOptions.compileOnSave; @@ -82341,6 +83226,9 @@ var ts; ProjectService.prototype.removeProject = function (project) { this.logger.info("remove project: " + project.getRootFiles().toString()); project.close(); + if (ts.Debug.shouldAssert(1)) { + this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project)); }); + } this.pendingProjectUpdates.delete(project.getProjectName()); switch (project.projectKind) { case server.ProjectKind.External: @@ -82579,7 +83467,7 @@ var ts; }; ProjectService.prototype.forEachConfigFileLocation = function (info, action, projectRootPath) { var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName)); - while (!projectRootPath || searchPath.indexOf(projectRootPath) >= 0) { + while (!projectRootPath || ts.containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames)) { var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); var result = action(tsconfigFileName, ts.combinePaths(canonicalSearchPath, "tsconfig.json")); @@ -82846,12 +83734,15 @@ var ts; project.watchWildcards(projectOptions.wildcardDirectories); } this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); + this.sendConfigFileDiagEvent(project, configFileName); + }; + ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { if (!this.eventHandler) { return; } this.eventHandler({ eventName: server.ConfigFileDiagEvent, - data: { configFileName: configFileName, diagnostics: project.getGlobalProjectErrors() || [], triggerFile: configFileName } + data: { configFileName: project.getConfigFilePath(), diagnostics: project.getAllProjectErrors(), triggerFile: triggerFile } }); }; ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (info, projectRootPath) { @@ -82859,9 +83750,10 @@ var ts; return undefined; } if (projectRootPath) { + var canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath); for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var project = _a[_i]; - if (project.projectRootPath === projectRootPath) { + if (project.projectRootPath === canonicalProjectRootPath) { return project; } } @@ -82889,9 +83781,9 @@ var ts; } return this.createInferredProject(undefined, true); }; - ProjectService.prototype.createInferredProject = function (rootDirectoryForResolution, isSingleInferredProject, projectRootPath) { + ProjectService.prototype.createInferredProject = function (currentDirectory, isSingleInferredProject, projectRootPath) { var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; - var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, rootDirectoryForResolution); + var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory); if (isSingleInferredProject) { this.inferredProjects.unshift(project); } @@ -83066,6 +83958,7 @@ var ts; ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { var _this = this; var configFileName; + var sendConfigFileDiagEvent = false; var configFileErrors; var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, fileContent, scriptKind, hasMixedContent); var project = this.findContainingExternalProject(fileName); @@ -83075,10 +83968,7 @@ var ts; project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { project = this.createConfiguredProject(configFileName); - var errors = project.getGlobalProjectErrors(); - if (errors && errors.length > 0) { - configFileErrors = errors; - } + sendConfigFileDiagEvent = true; } } } @@ -83086,9 +83976,15 @@ var ts; project.markAsDirty(); } if (info.isOrphan()) { + configFileName = undefined; + sendConfigFileDiagEvent = false; this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); } this.addToListOfOpenFiles(info); + if (sendConfigFileDiagEvent) { + configFileErrors = project.getAllProjectErrors(); + this.sendConfigFileDiagEvent(project, fileName); + } this.configuredProjects.forEach(function (project) { if (!project.hasOpenRef()) { _this.removeProject(project); @@ -84389,13 +85285,7 @@ var ts; } }; Session.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { - var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, false, projectRootPath), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - if (this.eventHandler) { - this.eventHandler({ - eventName: "configFileDiag", - data: { triggerFile: fileName, configFileName: configFileName, diagnostics: configFileErrors || server.emptyArray } - }); - } + this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, false, projectRootPath); }; Session.prototype.getPosition = function (args, scriptInfo) { return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); @@ -84936,7 +85826,7 @@ var ts; if (languageServiceDisabled) { return; } - var fileNamesInProject = fileNames.filter(function (value) { return value.indexOf("lib.d.ts") < 0; }); + var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); }); if (fileNamesInProject.length === 0) { return; } @@ -86346,10 +87236,20 @@ var ts; var logger = createLogger(); var sys = ts.sys; var useWatchGuard = process.platform === "win32" && ts.getNodeMajorVersion() >= 4; + var originalWatchDirectory = sys.watchDirectory.bind(sys); + var noopWatcher = { close: ts.noop }; + function watchDirectorySwallowingException(path, callback, recursive) { + try { + return originalWatchDirectory(path, callback, recursive); + } + catch (e) { + logger.info("Exception when creating directory watcher: " + e.message); + return noopWatcher; + } + } if (useWatchGuard) { var currentDrive_1 = extractWatchDirectoryCacheKey(sys.resolvePath(sys.getCurrentDirectory()), undefined); var statusCache_1 = ts.createMap(); - var originalWatchDirectory_1 = sys.watchDirectory; sys.watchDirectory = function (path, callback, recursive) { var cacheKey = extractWatchDirectoryCacheKey(path, currentDrive_1); var status = cacheKey && statusCache_1.get(cacheKey); @@ -86382,13 +87282,16 @@ var ts; logger.info("watchDirectory for " + path + " uses cached drive information."); } if (status) { - return originalWatchDirectory_1.call(sys, path, callback, recursive); + return watchDirectorySwallowingException(path, callback, recursive); } else { - return { close: function () { } }; + return noopWatcher; } }; } + else { + sys.watchDirectory = watchDirectorySwallowingException; + } sys.write = function (s) { return writeMessage(new Buffer(s, "utf8")); }; sys.watchFile = function (fileName, callback) { var watchedFile = pollingWatchedFileSet.addFile(fileName, callback); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 1feb6b7d073..151c948602d 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -1442,6 +1442,10 @@ declare namespace ts { interface JSDocUnknownTag extends JSDocTag { kind: SyntaxKind.JSDocTag; } + /** + * Note that `@extends` is a synonym of `@augments`. + * Both tags are represented by this interface. + */ interface JSDocAugmentsTag extends JSDocTag { kind: SyntaxKind.JSDocAugmentsTag; class: ExpressionWithTypeArguments & { @@ -1473,7 +1477,7 @@ declare namespace ts { interface JSDocPropertyLikeTag extends JSDocTag, Declaration { parent: JSDoc; name: EntityName; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ isNameFirst: boolean; isBracketed: boolean; @@ -1727,6 +1731,10 @@ declare namespace ts { signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + /** + * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead + * This will be removed in a future version. + */ getSymbolDisplayBuilder(): SymbolDisplayBuilder; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; @@ -2866,6 +2874,8 @@ declare namespace ts { function getJSDocReturnType(node: Node): TypeNode | undefined; /** Get all JSDoc tags related to a node, including those on parent nodes. */ function getJSDocTags(node: Node): ReadonlyArray | undefined; + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray | undefined; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -3058,6 +3068,8 @@ declare namespace ts { function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node: Node): boolean; + function isSetAccessor(node: Node): node is SetAccessorDeclaration; + function isGetAccessor(node: Node): node is GetAccessorDeclaration; } declare namespace ts { interface ErrorCallback { @@ -7104,7 +7116,7 @@ declare namespace ts.server { getScriptKind(fileName: string): ScriptKind; getScriptVersion(filename: string): string; getScriptSnapshot(filename: string): IScriptSnapshot; - getCancellationToken(): ThrottledCancellationToken; + getCancellationToken(): HostCancellationToken; getCurrentDirectory(): string; getDefaultLibFileName(): string; useCaseSensitiveFileNames(): boolean; @@ -7131,11 +7143,11 @@ declare namespace ts.server { enableLanguageService(): void; disableLanguageService(): void; getProjectName(): string; - abstract getProjectRootPath(): string | undefined; abstract getTypeAcquisition(): TypeAcquisition; getExternalFiles(): SortedReadonlyArray; getSourceFile(path: Path): SourceFile; close(): void; + private detachScriptInfoIfNotRoot(uncheckedFilename); isClosed(): boolean; hasRoots(): boolean; getRootFiles(): NormalizedPath[]; @@ -7176,15 +7188,15 @@ declare namespace ts.server { * the file and its imports/references are put into an InferredProject. */ class InferredProject extends Project { - readonly projectRootPath: string | undefined; private static readonly newName; private _isJsInferredProject; toggleJsInferredProject(isJsInferredProject: boolean): void; setCompilerOptions(options?: CompilerOptions): void; + /** this is canonical project root path */ + readonly projectRootPath: string | undefined; addRoot(info: ScriptInfo): void; removeRoot(info: ScriptInfo): void; isProjectWithSingleRoot(): boolean; - getProjectRootPath(): string; close(): void; getTypeAcquisition(): TypeAcquisition; } @@ -7211,7 +7223,6 @@ declare namespace ts.server { enablePlugins(): void; private enablePlugin(pluginConfigEntry, searchPaths); private enableProxy(pluginModuleFactory, configEntry); - getProjectRootPath(): string; /** * Get the errors that dont have any file name associated */ @@ -7237,11 +7248,9 @@ declare namespace ts.server { class ExternalProject extends Project { externalProjectName: string; compileOnSaveEnabled: boolean; - private readonly projectFilePath; excludedFiles: ReadonlyArray; private typeAcquisition; getExcludedFiles(): ReadonlyArray; - getProjectRootPath(): string; getTypeAcquisition(): TypeAcquisition; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; } @@ -7517,9 +7526,10 @@ declare namespace ts.server { private createConfiguredProject(configFileName); private updateNonInferredProjectFiles(project, files, propertyReader); private updateNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave); + private sendConfigFileDiagEvent(project, triggerFile); private getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath); private getOrCreateSingleInferredProjectIfEnabled(); - private createInferredProject(rootDirectoryForResolution, isSingleInferredProject?, projectRootPath?); + private createInferredProject(currentDirectory, isSingleInferredProject?, projectRootPath?); getScriptInfo(uncheckedFileName: string): ScriptInfo; private watchClosedScriptInfo(info); private stopWatchingScriptInfo(info); diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 04c80d5bbea..9983c5e6e64 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -1363,7 +1363,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.6"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -1542,10 +1542,12 @@ var ts; } ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { + var result = []; Debug.assert(arrayA.length === arrayB.length); for (var i = 0; i < arrayA.length; i++) { - callback(arrayA[i], arrayB[i], i); + result.push(callback(arrayA[i], arrayB[i], i)); } + return result; } ts.zipWith = zipWith; function zipToMap(keys, values) { @@ -1674,22 +1676,6 @@ var ts; return array; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var item = array_2[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var i = 0; i < array.length; i++) { @@ -1745,8 +1731,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1927,8 +1913,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (predicate(v)) { return true; } @@ -1954,8 +1940,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + loop: for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -2048,8 +2034,8 @@ var ts; ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; // Note: we need the following type assertion because of GH #17069 result += v[prop]; } @@ -2422,8 +2408,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; @@ -2864,7 +2850,7 @@ var ts; } ts.getDirectoryPath = getDirectoryPath; function isUrl(path) { - return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + return path && !isRootedDiskPath(path) && stringContains(path, "://"); } ts.isUrl = isUrl; function pathIsRelative(path) { @@ -3120,8 +3106,12 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; function hasExtension(fileName) { - return getBaseFileName(fileName).indexOf(".") >= 0; + return stringContains(getBaseFileName(fileName), "."); } ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { @@ -4686,6 +4676,7 @@ var ts; Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), 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."), @@ -5013,6 +5004,7 @@ var ts; A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), 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}'."), @@ -5336,9 +5328,10 @@ var ts; Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), - JSDoc_augments_is_not_attached_to_a_class_declaration: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_augments_is_not_attached_to_a_class_declaration_8022", "JSDoc '@augments' is not attached to a class declaration."), - JSDoc_augments_0_does_not_match_the_extends_1_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023", "JSDoc '@augments {0}' does not match the 'extends {1}' clause."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), 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."), @@ -5370,7 +5363,7 @@ 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(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), - Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'."), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), @@ -5384,6 +5377,7 @@ var ts; Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'."), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), @@ -5392,6 +5386,8 @@ var ts; Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Infer_type_of_0_from_usage: diag(95009, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95009", "Infer type of '{0}' from usage."), + Infer_parameter_types_from_usage: diag(95010, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95010", "Infer parameter types from usage."), }; })(ts || (ts = {})); /// @@ -6920,27 +6916,14 @@ var ts; } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { - return isRestParameter(ts.lastOrUndefined(s.parameters)); + var last = ts.lastOrUndefined(s.parameters); + return last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; - function hasDeclaredRestParameter(s) { - return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); - } - ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 274 /* JSDocVariadicType */ || - ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274 /* JSDocVariadicType */; })) { - return true; - } - } - return isDeclaredRestParam(node); + return node.dotDotDotToken !== undefined; } ts.isRestParameter = isRestParameter; - function isDeclaredRestParam(node) { - return node && node.dotDotDotToken !== undefined; - } - ts.isDeclaredRestParam = isDeclaredRestParam; var AssignmentKind; (function (AssignmentKind) { AssignmentKind[AssignmentKind["None"] = 0] = "None"; @@ -9223,27 +9206,35 @@ var ts; if (!declaration) { return undefined; } - if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143 /* QualifiedName */) { - return declaration.name.right; - } - if (declaration.kind === 194 /* BinaryExpression */) { - var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { - case 1 /* ExportsProperty */: - case 4 /* ThisProperty */: - case 5 /* Property */: - case 3 /* PrototypeProperty */: - return expr.left.name; - default: - return undefined; + switch (declaration.kind) { + case 284 /* JSDocPropertyTag */: + case 279 /* JSDocParameterTag */: { + var name = declaration.name; + if (name.kind === 143 /* QualifiedName */) { + return name.right; + } + break; + } + case 194 /* BinaryExpression */: { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + default: + return undefined; + } + } + case 283 /* JSDocTypedefTag */: + return getNameOfJSDocTypedef(declaration); + case 243 /* ExportAssignment */: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; } } - else if (declaration.kind === 283 /* JSDocTypedefTag */) { - return getNameOfJSDocTypedef(declaration); - } - else { - return declaration.name; - } + return declaration.name; } ts.getNameOfDeclaration = getNameOfDeclaration; /** @@ -9356,6 +9347,12 @@ var ts; var tags = getJSDocTags(node); return ts.find(tags, function (doc) { return doc.kind === kind; }); } + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node, kind) { + var tags = getJSDocTags(node); + return ts.filter(tags, function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -10706,6 +10703,14 @@ var ts; return node.kind >= 276 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 154 /* SetAccessor */; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 153 /* GetAccessor */; + } + ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ /* @internal */ function hasJSDocNodes(node) { @@ -18161,6 +18166,7 @@ var ts; if (tagName) { switch (tagName.escapedText) { case "augments": + case "extends": tag = parseAugmentsTag(atToken, tagName); break; case "class": @@ -18456,7 +18462,7 @@ var ts; if (typeExpression && typeExpression.type.kind === 164 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); } @@ -18732,8 +18738,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var node = array_7[_i]; visitNode(node); } } @@ -18870,8 +18876,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } return; @@ -22029,7 +22035,7 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : withoutAtTypePrefix; } @@ -22227,6 +22233,14 @@ var ts; // state used to aggregate transform flags during bind. var subtreeTransformFlags = 0 /* None */; var skipTransformFlagAggregation; + /** + * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) + * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) + * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. + */ + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } function bindSourceFile(f, opts) { file = f; options = opts; @@ -22301,6 +22315,9 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { + if (node.kind === 243 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } var name = ts.getNameOfDeclaration(node); if (name) { if (ts.isAmbientModule(node)) { @@ -22331,8 +22348,6 @@ var ts; return "__index" /* Index */; case 244 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 243 /* ExportAssignment */: - return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; case 194 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { // module.exports = ... @@ -22448,9 +22463,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } @@ -23183,7 +23198,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } if (!node.statement || node.statement.kind !== 212 /* DoStatement */) { // do statement sets current flow inside bindDoStatement @@ -23677,7 +23692,7 @@ var ts; !ts.isInAmbientContext(node)) { // Report error only if there are no parse errors in file if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); } } } @@ -23772,7 +23787,7 @@ var ts; } function checkStrictModeNumericLiteral(node) { if (inStrictMode && node.numericLiteralFlags & 4 /* Octal */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } function checkStrictModePostfixUnaryExpression(node) { @@ -24065,7 +24080,7 @@ var ts; // falls through case 284 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 272 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); @@ -24122,20 +24137,20 @@ var ts; } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } if (node.parent.kind !== 265 /* SourceFile */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { var parent_1 = node.parent; if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } } @@ -24174,15 +24189,12 @@ var ts; function isExportsOrModuleExportsOrAlias(node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); } function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (ts.isIdentifier(node)) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - return false; + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(node) { return isExportsOrModuleExportsOrAlias(node) || @@ -24246,17 +24258,19 @@ var ts; // follow the function declaration var leftSideOfAssignment = node.left; var target = leftSideOfAssignment.expression; - // Fix up parent pointers since we're going to use these nodes before we bind into them - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - // This can be an alias for the 'exports' or 'module.exports' names, e.g. - // var util = module.exports; - // util.property = function ... - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); + if (ts.isIdentifier(target)) { + // Fix up parent pointers since we're going to use these nodes before we bind into them + leftSideOfAssignment.parent = node; + target.parent = leftSideOfAssignment; + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); + } } } function lookupSymbolForName(name) { @@ -24312,7 +24326,7 @@ var ts; if (node.name) { node.name.parent = node; } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); } symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); prototypeSymbol.parent = symbol; @@ -24528,6 +24542,11 @@ var ts; } if (expression.kind === 91 /* ImportKeyword */) { transformFlags |= 67108864 /* 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 */; + } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; @@ -25643,6 +25662,23 @@ var ts; return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getBooleanType: function () { return booleanType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, isArrayLikeType: isArrayLikeType, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, @@ -25690,6 +25726,7 @@ var ts; anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var markerSuperType = createType(16384 /* TypeParameter */); var markerSubType = createType(16384 /* TypeParameter */); markerSubType.constraint = markerSuperType; @@ -25891,6 +25928,12 @@ var ts; CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; })(CheckMode || (CheckMode = {})); + var CallbackCheck; + (function (CallbackCheck) { + CallbackCheck[CallbackCheck["None"] = 0] = "None"; + CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; + CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; + })(CallbackCheck || (CallbackCheck = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); @@ -26259,6 +26302,7 @@ var ts; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; + var lastNonBlockLocation; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; @@ -26470,13 +26514,16 @@ var ts; } break; } + if (location.kind !== 207 /* Block */) { + lastNonBlockLocation = location; + } lastLocation = location; location = location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; } if (!result) { @@ -29195,13 +29242,13 @@ var ts; if (parentType === unknownType) { return unknownType; } - // If no type was specified or inferred for parent, or if the specified or inferred type is any, - // infer from the initializer of the binding element if one is present. Otherwise, go with the - // undefined or any type of the parent. - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } + // If no type was specified or inferred for parent, + // infer from the initializer of the binding element if one is present. + // Otherwise, go with the undefined type of the parent. + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { return parentType; } var type; @@ -29227,9 +29274,6 @@ var ts; // computed properties with non-literal names are treated as 'any' return anyType; } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } // 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. var text = ts.getTextOfPropertyName(name); @@ -30977,27 +31021,48 @@ var ts; function getApparentTypeOfIntersectionType(type) { return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); } + function getResolvedTypeParameterDefault(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + // To block recursion, set the initial value to the resolvingDefaultType. + typeParameter.default = resolvingDefaultType; + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + // If we have not been called recursively, set the correct default type. + typeParameter.default = defaultType; + } + } + } + else if (typeParameter.default === resolvingDefaultType) { + // If we are called recursively for this type parameter, mark the default as circular. + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } /** * Gets the default type for a type parameter. * * If the type parameter is the result of an instantiation, this gets the instantiated - * default type of its target. If the type parameter has no default type, `undefined` - * is returned. - * - * This function *does not* perform a circularity check. + * default type of its target. If the type parameter has no default type or the default is + * circular, `undefined` is returned. */ function getDefaultFromTypeParameter(typeParameter) { - if (!typeParameter.default) { - if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); - typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; - } - else { - var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; - } - } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + /** + * Indicates whether the declaration of a typeParameter has a default type. + */ + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, @@ -31161,7 +31226,7 @@ var ts; return getIndexTypeOfStructuredType(getApparentType(type), kind); } function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { + if (isObjectTypeWithInferableIndex(type)) { var propTypes = []; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; @@ -31265,7 +31330,7 @@ var ts; var minTypeArgumentCount = 0; if (typeParameters) { for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { + if (!hasTypeParameterDefault(typeParameters[i])) { minTypeArgumentCount = i + 1; } } @@ -32605,7 +32670,7 @@ var ts; * this function should be called in a left folding style, with left = previous result of getSpreadType * and right = the new element to be spread. */ - function getSpreadType(left, right) { + function getSpreadType(left, right, symbol, propagatedFlags) { if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { return anyType; } @@ -32616,10 +32681,10 @@ var ts; return left; } if (left.flags & 65536 /* Union */) { - return mapType(left, function (t) { return getSpreadType(t, right); }); + return mapType(left, function (t) { return getSpreadType(t, right, symbol, propagatedFlags); }); } if (right.flags & 65536 /* Union */) { - return mapType(right, function (t) { return getSpreadType(left, t); }); + return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } if (right.flags & 16777216 /* NonPrimitive */) { return nonPrimitiveType; @@ -32676,7 +32741,12 @@ var ts; members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); } } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var spread = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + spread.flags |= propagatedFlags; + spread.flags |= 1048576 /* FreshLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */; + spread.symbol = symbol; + return spread; } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { @@ -32978,11 +33048,11 @@ var ts; // The first time an anonymous type is instantiated we compute and store a list of the type // parameters that are in scope (and therefore potentially referenced). For type literals that // aren't the right hand side of a generic type alias declaration we optimize by reducing the - // set of type parameters to those that are actually referenced somewhere in the literal. + // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true) || ts.emptyArray; typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? - ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : outerTypeParameters; links.typeParameters = typeParameters; if (typeParameters.length) { @@ -33007,13 +33077,27 @@ var ts; } return type; } - function isTypeParameterReferencedWithin(tp, node) { - return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); - function checkThis(node) { - return node.kind === 169 /* ThisType */ || ts.forEachChild(node, checkThis); + function isTypeParameterPossiblyReferenced(tp, node) { + // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks + // between the node and the type parameter declaration, if the node contains actual references to the + // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_1 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 207 /* Block */ ? "quit" : n === container_1; })) { + return ts.forEachChild(node, containsReference); + } } - function checkIdentifier(node) { - return node.kind === 71 /* Identifier */ && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + return true; + function containsReference(node) { + switch (node.kind) { + case 169 /* ThisType */: + return tp.isThisType; + case 71 /* Identifier */: + return !tp.isThisType && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp; + case 162 /* TypeQuery */: + return true; + } + return ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -33214,13 +33298,13 @@ var ts; return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, /*checkAsCallback*/ false, ignoreReturnTypes, /*reportErrors*/ false, + return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; } /** * See signatureRelatedTo, compareSignaturesIdentical */ - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; @@ -33233,7 +33317,7 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = strictFunctionTypes && kind !== 151 /* MethodDeclaration */ && + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 151 /* MethodDeclaration */ && kind !== 150 /* MethodSignature */ && kind !== 152 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); @@ -33260,21 +33344,21 @@ var ts; for (var i = 0; i < checkCount; i++) { var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); // 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 - // function types with a single call signature, we known we are relating two callback parameters. In + // function types with a single call signature, we know we are relating two callback parameters. In // that case it is sufficient to only relate the parameters of the signatures co-variantly because, // similar to return values, callback parameters are output positions. This means that a Promise, // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) // with respect to T. + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && (getFalsyFlags(sourceType) & 6144 /* Nullable */) === (getFalsyFlags(targetType) & 6144 /* Nullable */); var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, /*checkAsCallback*/ true, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.symbolName(sourceParams[i < sourceMax ? i : sourceMax]), ts.symbolName(targetParams[i < targetMax ? i : targetMax])); @@ -33305,7 +33389,7 @@ var ts; // When relating callback signatures, we still need to relate return types bi-variantly as otherwise // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } // wouldn't be co-variant for T without this rule. - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || + result &= callbackCheck === 1 /* Bivariant */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || compareTypes(sourceReturnType, targetReturnType, reportErrors); } } @@ -33715,6 +33799,13 @@ var ts; (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } + if (target.flags & 65536 /* Union */) { + var discriminantType = findMatchingDiscriminantType(source, target); + if (discriminantType) { + // check excess properties against discriminant type only, not the entire union + return hasExcessProperties(source, discriminantType, reportErrors); + } + } var _loop_5 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -33791,22 +33882,25 @@ var ts; return 0 /* False */; } function findMatchingDiscriminantType(source, target) { + var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.escapedName)) { - 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)) { - return type; + var sourceProperty = findSingleDiscriminantProperty(sourceProperties, target); + if (sourceProperty) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var type = _a[_i]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); + if (targetType && isRelatedTo(sourceType, targetType)) { + if (match) { + return undefined; } + match = type; } } } } + return match; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -34264,8 +34358,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); if (!targetProp) { return 0 /* False */; @@ -34353,8 +34447,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, - /*checkAsCallback*/ false, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -34415,7 +34508,7 @@ var ts; // if T is related to U. return kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); } - if (isObjectLiteralType(source)) { + if (isObjectTypeWithInferableIndex(source)) { var related = -1 /* True */; if (kind === 0 /* String */) { var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); @@ -34885,11 +34978,11 @@ var ts; return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; } /** - * Return true if type was inferred from an object literal or written as an object type literal + * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module * with no call or construct signatures. */ - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */)) !== 0 && + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 512 /* ValueModule */)) !== 0 && getSignaturesOfType(type, 0 /* Call */).length === 0 && getSignaturesOfType(type, 1 /* Construct */).length === 0; } @@ -35696,6 +35789,19 @@ var ts; } return false; } + function findSingleDiscriminantProperty(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + return undefined; + } + result = sourceProperty; + } + } + return result; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -38177,7 +38283,7 @@ var ts; checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -38189,7 +38295,7 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return unknownType; } - spread = getSpreadType(spread, type); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags); offset = i + 1; continue; } @@ -38231,14 +38337,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768 /* Object */) { - // only set the symbol and flags if this is a (fresh) object type - spread.flags |= propagatedFlags; - spread.flags |= 1048576 /* FreshLiteral */; - spread.objectFlags |= 128 /* ObjectLiteral */; - spread.symbol = node.symbol; + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); } return spread; } @@ -38289,7 +38388,7 @@ var ts; */ function isUnhyphenatedJsxName(name) { // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers - return name.indexOf("-") < 0; + return !ts.stringContains(name, "-"); } /** * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name @@ -38348,7 +38447,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); attributesArray = []; attributesTable = ts.createSymbolTable(); } @@ -38357,7 +38456,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*propagatedFlags*/ 0); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -38367,7 +38466,7 @@ var ts; if (!hasSpreadAnyType) { if (spread !== emptyObjectType) { if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); } attributesArray = getPropertiesOfType(spread); } @@ -39740,29 +39839,27 @@ var ts; } return getInferredTypes(context); } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJavaScriptFile(signature.declaration); var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable /* so far */) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } + 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 && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + 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; } } - return typeArgumentsAreAssignable; + return typeArgumentTypes; } /** * Check if the given signature can possibly be a signature called by the JSX opening-like element. @@ -40240,8 +40337,7 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } else if (candidateForTypeArgumentError) { - var typeArguments_1 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -40291,14 +40387,14 @@ var ts; var candidate = candidates[bestIndex]; var typeParameters = candidate.typeParameters; if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_2 = node.typeArguments.map(getTypeOfNode); - while (typeArguments_2.length > typeParameters.length) { - typeArguments_2.pop(); + var typeArguments_1 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_1.length > typeParameters.length) { + typeArguments_1.pop(); } - while (typeArguments_2.length < typeParameters.length) { - typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + while (typeArguments_1.length < typeParameters.length) { + typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); } - var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + var instantiated = createSignatureInstantiation(candidate, typeArguments_1); candidates[bestIndex] = instantiated; return instantiated; } @@ -40333,10 +40429,12 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); - if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false)) { + var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (typeArgumentResult) { + typeArgumentTypes = typeArgumentResult; + } + else { candidateForTypeArgumentError = originalCandidate; break; } @@ -40344,6 +40442,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { @@ -40612,6 +40711,11 @@ var ts; if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; @@ -40622,6 +40726,18 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); } + /** + * Sometimes, we have a decorator that could accept zero arguments, + * but is receiving too many arguments as part of the decorator invocation. + * In those cases, a user may have meant to *call* the expression before using it as a decorator. + */ + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, 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 @@ -42305,6 +42421,9 @@ var ts; if (!hasNonCircularBaseConstraint(typeParameter)) { error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } var constraintType = getConstraintOfTypeParameter(typeParameter); var defaultType = getDefaultFromTypeParameter(typeParameter); if (constraintType && defaultType) { @@ -42324,7 +42443,6 @@ var ts; checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - func = ts.getContainingFunction(node); if (!(func.kind === 152 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } @@ -43681,17 +43799,22 @@ var ts; } } function checkJSDocAugmentsTag(node) { - var cls = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(cls) && !ts.isClassExpression(cls)) { - error(cls, ts.Diagnostics.JSDoc_augments_is_not_attached_to_a_class_declaration); + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } + var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 277 /* JSDocAugmentsTag */); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } var name = getIdentifierFromEntityNameExpression(node.class.expression); - var extend = ts.getClassExtendsHeritageClauseElement(cls); + var extend = ts.getClassExtendsHeritageClauseElement(classLike); if (extend) { var className = getIdentifierFromEntityNameExpression(extend.expression); if (className && name.escapedText !== className.escapedText) { - error(name, ts.Diagnostics.JSDoc_augments_0_does_not_match_the_extends_1_clause, ts.idText(name), ts.idText(className)); + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); } } } @@ -43941,7 +44064,7 @@ var ts; } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -48704,6 +48827,9 @@ var ts; // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). + if (node === undefined) { + return undefined; + } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; setOriginalNode(clone, node); @@ -50970,6 +51096,16 @@ var ts; return node; } ts.setEmitFlags = setEmitFlags; + /** + * Sets flags that control emit behavior of a node. + */ + /* @internal */ + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; /** * Gets a custom text range to use when emitting source maps. */ @@ -53766,6 +53902,19 @@ var ts; } return values; } + /** + * Used in the module transformer to check if an expression is reasonably without sideeffect, + * and thus better to copy into multiple places rather than to cache in a temporary variable + * - this is mostly subjective beyond the requirement that the expression not be sideeffecting + */ + function isSimpleCopiableExpression(expression) { + return expression.kind === 9 /* StringLiteral */ || + expression.kind === 8 /* NumericLiteral */ || + expression.kind === 13 /* NoSubstitutionTemplateLiteral */ || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; })(ts || (ts = {})); /// /// @@ -54237,7 +54386,7 @@ var ts; ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; - ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; + ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; @@ -54248,6 +54397,7 @@ var ts; var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = typeof compilerOptions.strictNullChecks === "undefined" ? compilerOptions.strict : compilerOptions.strictNullChecks; var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); // Save the previous transformation hooks. @@ -54679,8 +54829,9 @@ var ts; var facts = 0 /* None */; if (ts.some(staticProperties)) facts |= 1 /* HasStaticInitializedProperties */; - if (ts.getClassExtendsHeritageClauseElement(node)) - facts |= 64 /* HasExtendsClause */; + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) + facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) facts |= 2 /* HasConstructorDecorators */; if (ts.childIsDecorated(node)) @@ -54804,7 +54955,7 @@ var ts; : undefined; var classDeclaration = ts.createClassDeclaration( /*decorators*/ undefined, modifiers, name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0)); // To better align with the old emitter, we should not emit a trailing source map // entry if the class has static properties. var emitFlags = ts.getEmitFlags(node); @@ -54913,7 +55064,7 @@ var ts; // ${members} // } var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0); + var members = transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0); var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, location); @@ -54969,11 +55120,11 @@ var ts; * Transforms the members of a class. * * @param node The current class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformClassMembers(node, hasExtendsClause) { + function transformClassMembers(node, isDerivedClass) { var members = []; - var constructor = transformConstructor(node, hasExtendsClause); + var constructor = transformConstructor(node, isDerivedClass); if (constructor) { members.push(constructor); } @@ -54984,9 +55135,9 @@ var ts; * Transforms (or creates) a constructor for a class. * * @param node The current class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformConstructor(node, hasExtendsClause) { + function transformConstructor(node, isDerivedClass) { // 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 @@ -54999,7 +55150,7 @@ var ts; return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause); + var body = transformConstructorBody(node, constructor, isDerivedClass); // constructor(${parameters}) { // ${body} // } @@ -55012,7 +55163,6 @@ var ts; * parameter property assignments or instance property initializers. * * @param constructor The constructor declaration. - * @param hasExtendsClause A value indicating whether the class has an extends clause. */ function transformConstructorParameters(constructor) { // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: @@ -55039,9 +55189,9 @@ var ts; * * @param node The current class. * @param constructor The current class constructor. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformConstructorBody(node, constructor, hasExtendsClause) { + function transformConstructorBody(node, constructor, isDerivedClass) { var statements = []; var indexOfFirstStatement = 0; resumeLexicalEnvironment(); @@ -55062,7 +55212,7 @@ var ts; var propertyAssignments = getParametersWithPropertyAssignments(constructor); ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); } - else if (hasExtendsClause) { + else if (isDerivedClass) { // Add a synthetic `super` call: // // super(...arguments); @@ -55792,6 +55942,15 @@ var ts; var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 168 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 130 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 139 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } var serializedIndividual = serializeTypeNode(typeNode); if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { // One of the individual is global object, return immediately @@ -55811,7 +55970,7 @@ var ts; } } // If we were able to find common type, use it - return serializedUnion; + return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never } /** * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with @@ -62501,7 +62660,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { - if (ts.forEach(node.arguments, containsYield)) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { // [source] // a.b(1, yield, 2); // @@ -64366,7 +64525,7 @@ var ts; default: return transformCommonJSModule; } } - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -64721,17 +64880,19 @@ var ts; } } function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: - return transformImportCallExpressionAMD(node); + return createImportCallExpressionAMD(argument, containsLexicalThis); case ts.ModuleKind.UMD: - return transformImportCallExpressionUMD(node); + return createImportCallExpressionUMD(argument, containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return transformImportCallExpressionCommonJS(node); + return createImportCallExpressionCommonJS(argument, containsLexicalThis); } } - function transformImportCallExpressionUMD(node) { + function createImportCallExpressionUMD(arg, containsLexicalThis) { // (function (factory) { // ... (regular UMD) // } @@ -64746,12 +64907,22 @@ var ts; // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ // }); needUMDDynamicImportHelper = true; - return ts.createConditional( - /*condition*/ ts.createIdentifier("__syncRequire"), - /*whenTrue*/ transformImportCallExpressionCommonJS(node), - /*whenFalse*/ transformImportCallExpressionAMD(node)); + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */); + return ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); + } } - function transformImportCallExpressionAMD(node) { + function createImportCallExpressionAMD(arg, containsLexicalThis) { // improt("./blah") // emit as // define(["require", "exports", "blah"], function (require, exports) { @@ -64760,30 +64931,71 @@ var ts; // }); var resolve = ts.createUniqueName("resolve"); var reject = ts.createUniqueName("reject"); - return ts.createNew(ts.createIdentifier("Promise"), - /*typeArguments*/ undefined, [ts.createFunctionExpression( + var parameters = [ + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + ]; + var body = ts.createBlock([ + ts.createStatement(ts.createCall(ts.createIdentifier("require"), + /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, body); + } + else { + func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), - ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)], - /*type*/ undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), - /*typeArguments*/ undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); } - function transformImportCallExpressionCommonJS(node) { + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { // import("./blah") // emit as // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ // We have to wrap require in then callback so that require is done in asynchronously // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately - return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []), "then"), - /*typeArguments*/ undefined, [ts.createFunctionExpression( + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); + var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, requireCall); + } + else { + func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, - /*parameters*/ undefined, - /*type*/ undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, node.arguments))]))]); + /*parameters*/ [], + /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)])); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); } /** * Visits an ImportDeclaration node. @@ -64939,10 +65151,10 @@ var ts; if (original && hasAssociatedEndOfDeclarationMarker(original)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); } return ts.singleOrMany(statements); } @@ -66682,7 +66894,7 @@ var ts; // }; // }); return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), - /*typeArguments*/ undefined, node.arguments); + /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); } /** * Visits a DestructuringAssignment to flatten destructuring to exported symbols. @@ -67519,7 +67731,7 @@ var ts; }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); - return comment.indexOf("@internal") >= 0; + return ts.stringContains(comment, "@internal"); } function stripInternal(node) { if (node) { @@ -70899,7 +71111,7 @@ var ts; // check if numeric literal is a decimal literal that was originally written with a dot var text = getLiteralTextOfNode(expression); return !expression.numericLiteralFlags - && text.indexOf(ts.tokenToString(23 /* DotToken */)) < 0; + && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -72643,8 +72855,7 @@ var ts; existingInfo.version = sourceFile.version; emitHandler.onUpdateSourceFile(program, sourceFile); } - else if (program.hasInvalidatedResolution(sourceFile.path) && - emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { + else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { registerChangedFile(sourceFile.path, sourceFile.fileName); } } @@ -73529,8 +73740,7 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, - hasInvalidatedResolution: hasInvalidatedResolution + redirectTargetsSet: redirectTargetsSet }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -73902,10 +74112,17 @@ var ts; if (file.hasNoDefaultLib) { return true; } - if (defaultLibraryPath && defaultLibraryPath.length !== 0) { - return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, /*ignoreCase*/ !host.useCaseSensitiveFileNames()); + if (!options.noLib) { + return false; + } + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + if (!options.lib) { + return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + else { + return ts.forEach(options.lib, function (libFileName) { return ts.compareStrings(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; }); } - return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); @@ -76511,6 +76728,64 @@ var ts; return position; } ts.getSourceFileImportLocation = getSourceFileImportLocation; + /** + * Creates a deep, memberwise clone of a node with no source map location. + * + * WARNING: This is an expensive operation and is only intended to be used in refactorings + * and code fixes (because those are triggered by explicit user actions). + */ + function getSynthesizedDeepClone(node) { + if (node === undefined) { + return undefined; + } + var visited = 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; + } + else if (ts.isNumericLiteral(clone_7)) { + clone_7.numericLiteralFlags = node.numericLiteralFlags; + } + clone_7.pos = node.pos; + clone_7.end = node.end; + return clone_7; + } + // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update + // the new node created by visitEachChild with the extra changes getSynthesizedClone + // would have made. + visited.parent = undefined; + return visited; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + /** + * Sets EmitFlags to suppress leading and trailing trivia on the node. + */ + /* @internal */ + function suppressLeadingAndTrailingTrivia(node) { + ts.Debug.assert(node !== undefined); + suppressLeading(node); + suppressTrailing(node); + function suppressLeading(node) { + ts.addEmitFlags(node, 512 /* NoLeadingComments */); + var firstChild = ts.forEachChild(node, function (child) { return child; }); + firstChild && suppressLeading(firstChild); + } + function suppressTrailing(node) { + ts.addEmitFlags(node, 1024 /* NoTrailingComments */); + var lastChild = undefined; + ts.forEachChild(node, function (child) { return (lastChild = child, undefined); }, function (children) { + // As an optimization, jump straight to the end of the list. + if (children.length) { + lastChild = ts.last(children); + } + return undefined; + }); + lastChild && suppressTrailing(lastChild); + } + } + ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; })(ts || (ts = {})); // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. @@ -78178,7 +78453,7 @@ var ts; var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = fragment.indexOf(ts.directorySeparator) !== -1; + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); @@ -78210,7 +78485,7 @@ var ts; } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module - var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; + var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; // Get modules that the type checker picked up var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); @@ -79513,6 +79788,11 @@ var ts; if (ts.isClassLike(location)) { return location; } + // class c { method() { } b| } + if (isFromClassElementDeclaration(location) && + location.parent.name === location) { + return location.parent.parent; + } break; default: if (isFromClassElementDeclaration(contextToken) && @@ -81185,9 +81465,6 @@ var ts; return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { - if (ts.isExportAssignment(decl)) { - return ts.isIdentifier(decl.expression) ? decl.expression.escapedText : undefined; - } var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 /* Identifier */ && name.escapedText; }); @@ -81626,7 +81903,7 @@ var ts; State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(this.checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { @@ -86243,13 +86520,19 @@ var ts; } if (symbolFlags & 2097152 /* Alias */) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 236 /* NamespaceExportDeclaration */) { - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129 /* NamespaceKeyword */)); - } - else { - displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); + switch (symbol.declarations[0].kind) { + case 236 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(129 /* NamespaceKeyword */)); + break; + case 243 /* ExportAssignment */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -90129,6 +90412,29 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var decorator = ts.getAncestor(token, 147 /* Decorator */); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), + changes: changeTracker.getChanges() + }]; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -90284,7 +90590,7 @@ var ts; var className = classDeclaration.name.getText(); var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); + staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var initializeStaticAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), changes: staticInitializationChangeTracker.getChanges() @@ -90299,7 +90605,7 @@ var ts; } var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + propertyInitializationChangeTracker.insertNodeBefore(classDeclarationSourceFile, classConstructor.body.getLastToken(), propertyInitialization, { suffix: context.newLineCharacter }); var initializeAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), changes: propertyInitializationChangeTracker.getChanges() @@ -90880,9 +91186,6 @@ var ts; this.symbolIdToActionMap = []; } ImportCodeActionMap.prototype.addAction = function (symbolId, newAction) { - if (!newAction) { - return; - } var actions = this.symbolIdToActionMap[symbolId]; if (!actions) { this.symbolIdToActionMap[symbolId] = [newAction]; @@ -90901,7 +91204,7 @@ var ts; continue; } switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) { - case ModuleSpecifierComparison.Better: + case 0 /* Better */: // the new one is not worth considering if it is a new import. // However if it is instead a insertion into existing import, the user might want to use // the module specifier even it is worse by our standards. So keep it. @@ -90909,7 +91212,7 @@ var ts; return; } // falls through - case ModuleSpecifierComparison.Equal: + case 1 /* Equal */: // the current one is safe. But it is still possible that the new one is worse // than another existing one. For example, you may have new imports from "./foo/bar" // and "bar", when the new one is "bar/bar2" and the current one is "./foo/bar". The new @@ -90917,7 +91220,7 @@ var ts; // but the new one is worse than the other one, so should not add to the list. updatedNewImports.push(existingAction); break; - case ModuleSpecifierComparison.Worse: + case 2 /* Worse */: // the existing one is worse, remove from the list. continue; } @@ -90941,14 +91244,14 @@ var ts; }; ImportCodeActionMap.prototype.compareModuleSpecifiers = function (moduleSpecifier1, moduleSpecifier2) { if (moduleSpecifier1 === moduleSpecifier2) { - return ModuleSpecifierComparison.Equal; + return 1 /* Equal */; } // if moduleSpecifier1 (ms1) is a substring of ms2, then it is better if (moduleSpecifier2.indexOf(moduleSpecifier1) === 0) { - return ModuleSpecifierComparison.Better; + return 0 /* Better */; } if (moduleSpecifier1.indexOf(moduleSpecifier2) === 0) { - return ModuleSpecifierComparison.Worse; + return 2 /* Worse */; } // if both are relative paths, and ms1 has fewer levels, then it is better if (ts.isExternalModuleNameRelative(moduleSpecifier1) && ts.isExternalModuleNameRelative(moduleSpecifier2)) { @@ -90956,13 +91259,13 @@ var ts; var moduleSpecifier1LevelCount = (moduleSpecifier1.match(regex) || []).length; var moduleSpecifier2LevelCount = (moduleSpecifier2.match(regex) || []).length; return moduleSpecifier1LevelCount < moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Better + ? 0 /* Better */ : moduleSpecifier1LevelCount === moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Equal - : ModuleSpecifierComparison.Worse; + ? 1 /* Equal */ + : 2 /* Worse */; } // the equal cases include when the two specifiers are not comparable. - return ModuleSpecifierComparison.Equal; + return 1 /* Equal */; }; return ImportCodeActionMap; }()); @@ -91734,6 +92037,574 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + ], + getCodeActions: getActionsForAddExplicitTypeAnnotation + }); + function getActionsForAddExplicitTypeAnnotation(_a) { + var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var writer; + if (ts.isInJavaScriptFile(token)) { + return undefined; + } + switch (token.kind) { + case 71 /* Identifier */: + case 24 /* DotDotDotToken */: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + // Allowed + break; + default: + return undefined; + } + var containingFunction = ts.getContainingFunction(token); + var checker = program.getTypeChecker(); + switch (errorCode) { + // Variable and Property declarations + 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: + return getCodeActionForVariableDeclaration(token.parent); + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: + return getCodeActionForVariableUsage(token); + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessor(containingFunction)) { + return getCodeActionForSetAccessor(containingFunction); + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + return getCodeActionForParameters(token.parent); + // 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: + return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined; + } + return undefined; + function getCodeActionForVariableDeclaration(declaration) { + if (!ts.isIdentifier(declaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(declaration.name); + var typeString = type && typeToString(type, declaration); + if (!typeString) { + return undefined; + } + return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), ": " + typeString); + } + function getCodeActionForVariableUsage(token) { + var symbol = checker.getSymbolAtLocation(token); + return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration); + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 152 /* Constructor */: + return true; + case 186 /* FunctionExpression */: + return !!declaration.name; + } + return false; + } + function getCodeActionForParameters(parameterDeclaration) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return undefined; + } + var types = inferTypeForParametersFromUsage(containingFunction) || + ts.map(containingFunction.parameters, function (p) { return ts.isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name); }); + if (!types) { + return undefined; + } + var textChanges = ts.zipWith(containingFunction.parameters, types, function (parameter, type) { + if (type && !parameter.type && !parameter.initializer) { + var typeString = typeToString(type, containingFunction); + return typeString ? { + span: { start: parameter.end, length: 0 }, + newText: ": " + typeString + } : undefined; + } + }).filter(function (c) { return !!c; }); + return textChanges.length ? [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: textChanges + }] + }] : undefined; + } + function getCodeActionForSetAccessor(setAccessorDeclaration) { + var setAccessorParameter = setAccessorDeclaration.parameters[0]; + if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) || + inferTypeForVariableFromUsage(setAccessorParameter.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), ": " + typeString); + } + function getCodeActionForGetAccessor(getAccessorDeclaration) { + if (!ts.isIdentifier(getAccessorDeclaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + var closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, 20 /* CloseParenToken */); + return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), ": " + typeString); + } + function createCodeActions(name, start, typeString) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_type_of_0_from_usage), [name]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: start, length: 0 }, + newText: typeString + }] + }] + }]; + } + function getReferences(token) { + var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), token.getSourceFile(), token.getStart()); + ts.Debug.assert(!!references, "Found no references!"); + ts.Debug.assert(references.length === 1, "Found more references than expected"); + return ts.map(references[0].references, function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false); }); + } + function inferTypeForVariableFromUsage(token) { + return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken); + } + function inferTypeForParametersFromUsage(containingFunction) { + switch (containingFunction.kind) { + case 152 /* Constructor */: + case 186 /* FunctionExpression */: + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + var isConstructor = containingFunction.kind === 152 /* Constructor */; + var searchToken = isConstructor ? + getFirstChildOfKind(containingFunction, sourceFile, 123 /* ConstructorKeyword */) : + containingFunction.name; + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken); + } + } + } + function getTypeAccessiblityWriter() { + if (!writer) { + var str_1 = ""; + var typeIsAccessible_1 = true; + var writeText = function (text) { return str_1 += text; }; + writer = { + string: function () { return typeIsAccessible_1 ? str_1 : undefined; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + writeLine: function () { return str_1 += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { str_1 = ""; typeIsAccessible_1 = true; }, + trackSymbol: function (symbol, declaration, meaning) { + if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { + typeIsAccessible_1 = false; + } + }, + reportInaccessibleThisError: function () { typeIsAccessible_1 = false; }, + reportPrivateInBaseOfClassExpression: function () { typeIsAccessible_1 = false; }, + }; + } + writer.clear(); + return writer; + } + function typeToString(type, enclosingDeclaration) { + var writer = getTypeAccessiblityWriter(); + checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); + return writer.string(); + } + function getFirstChildOfKind(node, sourcefile, kind) { + for (var _i = 0, _a = node.getChildren(sourcefile); _i < _a.length; _i++) { + var child = _a[_i]; + if (child.kind === kind) + return child; + } + return undefined; + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypeFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return getTypeFromUsageContext(usageContext, checker); + } + InferFromReference.inferTypeFromReferences = inferTypeFromReferences; + function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { + if (declaration.parameters) { + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var isConstructor = declaration.kind === 152 /* Constructor */; + var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; + if (callContexts) { + var paramTypes = []; + for (var parameterIndex = 0; parameterIndex < declaration.parameters.length; parameterIndex++) { + var types = []; + var isRestParameter_1 = ts.isRestParameter(declaration.parameters[parameterIndex]); + for (var _a = 0, callContexts_1 = callContexts; _a < callContexts_1.length; _a++) { + var callContext = callContexts_1[_a]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter_1) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + paramTypes[parameterIndex] = isRestParameter_1 ? checker.createArrayType(type) : type; + } + } + return paramTypes; + } + } + return undefined; + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 193 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 192 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 194 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 257 /* CaseClause */: + case 258 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 181 /* CallExpression */: + case 182 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 179 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 180 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isPartOfExpression(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + usageContext.isNumber = true; + break; + case 37 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 40 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: + // ShiftOperator + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 48 /* AmpersandToken */: + case 49 /* BarToken */: + case 50 /* CaretToken */: + // CompoundAssignmentOperator + case 60 /* MinusEqualsToken */: + case 62 /* AsteriskAsteriskEqualsToken */: + case 61 /* AsteriskEqualsToken */: + case 63 /* SlashEqualsToken */: + case 64 /* PercentEqualsToken */: + case 68 /* AmpersandEqualsToken */: + case 69 /* BarEqualsToken */: + case 70 /* CaretEqualsToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 38 /* MinusToken */: + // RelationalOperator + case 27 /* LessThanToken */: + case 30 /* LessThanEqualsToken */: + case 29 /* GreaterThanToken */: + case 31 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 272 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 59 /* PlusEqualsToken */: + case 37 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 272 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 84 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 262178 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 58 /* EqualsToken */: + case 32 /* EqualsEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 92 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 54 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 226 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 53 /* AmpersandAmpersandToken */: + case 26 /* CommaToken */: + case 93 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 181 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 84 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function getTypeFromUsageContext(usageContext, checker) { + if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { + return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); + } + else if (usageContext.isNumber) { + return checker.getNumberType(); + } + else if (usageContext.isString) { + return checker.getStringType(); + } + else if (usageContext.candidateTypes) { + return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), /*subtypeReduction*/ true)); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); + var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + return checker.createPromiseType(types.length ? checker.getUnionType(types, /*subtypeReduction*/ true) : checker.getAnyType()); + } + 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) { + var members_4 = 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); + members_4.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.numberIndexContext) { + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); + } + return checker.createAnonymousType(/*symbol*/ undefined, members_4, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + return undefined; + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = getTypeFromUsageContext(callContext.returnType, checker); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 8192 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return usageContext && usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/// /// /// /// @@ -91748,6 +92619,7 @@ var ts; /// /// /// +/// /* @internal */ var ts; (function (ts) { @@ -91901,7 +92773,8 @@ var ts; switch (assignmentBinaryExpression.right.kind) { case 186 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); copyComments(assignmentBinaryExpression, method); return method; @@ -91918,7 +92791,8 @@ var ts; var expression = arrowFunctionBody; bodyBlock = ts.createBlock([ts.createReturn(expression)]); } - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); copyComments(assignmentBinaryExpression, method); return method; @@ -91963,7 +92837,8 @@ var ts; if (initializer.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; @@ -91973,11 +92848,15 @@ var ts; if (node.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } } })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); @@ -92110,7 +92989,7 @@ var ts; Messages.FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); Messages.CannotExtractIdentifier = createMessage("Select more than a single identifier."); Messages.CannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); - Messages.CannotCombineWritesAndReturns = createMessage("Cannot combine writes and returns"); + Messages.CannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); Messages.CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); Messages.CannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); @@ -92298,7 +93177,7 @@ var ts; permittedJumps = 0 /* None */; break; case 207 /* Block */: - if (node.parent && node.parent.kind === 224 /* TryStatement */ && node.finallyBlock === node) { + if (node.parent && node.parent.kind === 224 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } @@ -92395,7 +93274,10 @@ var ts; // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class var containingClass = ts.getContainingClass(current); if (containingClass) { - return [containingClass]; + var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration); + return containingFunction + ? [containingFunction, containingClass] + : [containingClass]; } } var start = current; @@ -92421,14 +93303,15 @@ var ts; return scopes; } function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope; + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); context.cancellationToken.throwIfCancellationRequested(); - return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); } function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope; + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); context.cancellationToken.throwIfCancellationRequested(); var expression = ts.isExpression(target) ? target @@ -92546,7 +93429,7 @@ var ts; })(SpecialScope || (SpecialScope = {})); function getUniqueName(baseName, fileText) { var nameText = baseName; - for (var i = 1; fileText.indexOf(nameText) !== -1; i++) { + for (var i = 1; ts.stringContains(fileText, nameText); i++) { nameText = baseName + "_" + i; } return nameText; @@ -92555,7 +93438,7 @@ var ts; * Result of 'extractRange' operation for a specific scope. * Stores either a list of changes that should be applied to extract a range or a list of errors */ - function extractFunctionInScope(node, scope, _a, range, context) { + function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted function @@ -92601,9 +93484,10 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType); + returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); } - var _b = transformFunctionBody(node, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + ts.suppressLeadingAndTrailingTrivia(body); var newFunction; if (ts.isClassLike(scope)) { // always create private method in TypeScript files @@ -92629,7 +93513,10 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); } else { - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { + prefix: ts.isLineBreak(file.text.charCodeAt(scope.getLastToken().pos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter, + suffix: context.newLineCharacter + }); } var newNodes = []; // replace range with function call @@ -92642,33 +93529,89 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { call = ts.createAwait(call); } - if (writes) { + if (exposedVariableDeclarations.length && !writes) { + // No need to mix declarations and writes. + // How could any variables be exposed if there's a return statement? + ts.Debug.assert(!returnValueProperty); + ts.Debug.assert(!(range.facts & RangeFacts.HasReturn)); + if (exposedVariableDeclarations.length === 1) { + // Declaring exactly one variable: let x = newFunction(); + var variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns + variableDeclaration.parent.flags))); + } + else { + // Declaring multiple variables / return properties: + // let {x, y} = newFunction(); + var bindingElements = []; + var typeElements = []; + var commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + var sawExplicitType = false; + for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { + var variableDeclaration = exposedVariableDeclarations_1[_i]; + bindingElements.push(ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, + /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); + // Being returned through an object literal will have widened the type. + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + typeElements.push(ts.createPropertySignature( + /*modifiers*/ undefined, + /*name*/ variableDeclaration.symbol.name, + /*questionToken*/ undefined, + /*type*/ variableType, + /*initializer*/ undefined)); + sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined; + if (typeLiteral) { + ts.setEmitFlags(typeLiteral, 1 /* SingleLine */); + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), + /*type*/ typeLiteral, + /*initializer*/ call)], commonNodeFlags))); + } + } + else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping. + for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) { + var variableDeclaration = exposedVariableDeclarations_2[_c]; + var flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */) { + flags = (flags & ~2 /* Const */) | 1 /* Let */; + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags))); + } + } if (returnValueProperty) { // has both writes and return, need to create variable declaration to hold return value; newNodes.push(ts.createVariableStatement( - /*modifiers*/ undefined, [ts.createVariableDeclaration(returnValueProperty, ts.createKeywordTypeNode(119 /* AnyKeyword */))])); + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */))); } - var assignments = getPropertyAssignmentsForWrites(writes); + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (returnValueProperty) { assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); } // propagate writes back if (assignments.length === 1) { - if (returnValueProperty) { - newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); - } - else { - newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58 /* EqualsToken */, call))); - if (range.facts & RangeFacts.HasReturn) { - newNodes.push(ts.createReturn()); - } + // We would only have introduced a return value property if there had been + // other assignments to make. + ts.Debug.assert(!returnValueProperty); + newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); } } else { // emit e.g. // { a, b, __return } = newFunction(a, b); // return __return; - newNodes.push(ts.createStatement(ts.createBinary(ts.createObjectLiteral(assignments), 58 /* EqualsToken */, call))); + newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call))); if (returnValueProperty) { newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); } @@ -92685,20 +93628,28 @@ var ts; newNodes.push(call); } } - if (isReadonlyArray(range.range)) { - changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes, { - nodeSeparator: context.newLineCharacter, - suffix: context.newLineCharacter // insert newline only when replacing statements - }); - } - else { - changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); - } + var replacementRange = isReadonlyArray(range.range) + ? { pos: ts.first(range.range).getStart(), end: ts.last(range.range).end } + : { pos: range.range.getStart(), end: range.range.end }; + changeTracker.replaceRangeWithNodes(context.file, replacementRange, newNodes, { nodeSeparator: context.newLineCharacter }); var edits = changeTracker.getChanges(); var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; var renameFilename = renameRange.getSourceFile().fileName; var renameLocation = getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === undefined) { + return undefined; + } + var clone = ts.getSynthesizedDeepClone(typeNode); + var withoutParens = clone; + while (ts.isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 139 /* UndefinedKeyword */; }) + ? clone + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(139 /* UndefinedKeyword */)]); + } } /** * Result of 'extractRange' operation for a specific scope. @@ -92713,8 +93664,9 @@ var ts; var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS ? undefined - : checker.typeToTypeNode(checker.getContextualType(node)); + : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); var initializer = transformConstantInitializer(node, substitutions); + ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); if (ts.isClassLike(scope)) { ts.Debug.assert(!isJS); // See CannotExtractToJSClass @@ -92735,7 +93687,7 @@ var ts; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, { suffix: context.newLineCharacter + context.newLineCharacter }); // Consume - changeTracker.replaceNodeWithNodes(context.file, node, [localReference], { nodeSeparator: context.newLineCharacter }); + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); } else { var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); @@ -92885,21 +93837,22 @@ var ts; return functionReference; } } - function transformFunctionBody(body, writes, substitutions, hasReturn) { - if (ts.isBlock(body) && !writes && substitutions.size === 0) { - // already block, no writes to propagate back, no substitutions - can use node as is + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) { + var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; + if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { + // already block, no declarations or writes to propagate back, no substitutions - can use node as is return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; } var returnValueProperty; var ignoreReturns = false; var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions - if (writes || substitutions.size) { + if (hasWritesOrVariableDeclarations || substitutions.size) { var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); - if (writes && !hasReturn && ts.isStatement(body)) { + if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) { // add return at the end to propagate writes back in case if control flow falls out of the function body // it is ok to know that range has at least one return since it we only allow unconditional returns - var assignments = getPropertyAssignmentsForWrites(writes); + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (assignments.length === 1) { rewrittenStatements.push(ts.createReturn(assignments[0].name)); } @@ -92913,8 +93866,8 @@ var ts; return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 219 /* ReturnStatement */ && writes) { - var assignments = getPropertyAssignmentsForWrites(writes); + if (!ignoreReturns && node.kind === 219 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { returnValueProperty = "__return"; @@ -92932,7 +93885,7 @@ var ts; var oldIgnoreReturns = ignoreReturns; ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node); var substitution = substitutions.get(ts.getNodeId(node).toString()); - var result = substitution ? substitution() : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); ignoreReturns = oldIgnoreReturns; return result; } @@ -92944,7 +93897,7 @@ var ts; : initializer; function visitor(node) { var substitution = substitutions.get(ts.getNodeId(node).toString()); - return substitution ? substitution() : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); } } function getStatementsOrClassElements(scope) { @@ -92979,8 +93932,8 @@ var ts; ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. var prevMember = undefined; var allProperties = true; - for (var _i = 0, members_4 = members; _i < members_4.length; _i++) { - var member = members_4[_i]; + for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { + var member = members_5[_i]; if (member.pos > maxPos) { return prevMember || members[0]; } @@ -93025,8 +93978,14 @@ var ts; } } } - function getPropertyAssignmentsForWrites(writes) { - return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); + var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + return variableAssignments === undefined + ? writeAssignments + : writeAssignments === undefined + ? variableAssignments + : variableAssignments.concat(writeAssignments); } function isReadonlyArray(v) { return ts.isArray(v); @@ -93059,6 +94018,9 @@ var ts; var functionErrorsPerScope = []; var constantErrorsPerScope = []; var visibleDeclarationsInExtractedRange = []; + var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID + var exposedVariableDeclarations = []; + var firstExposedNonVariableDeclaration = undefined; var expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) @@ -93097,7 +94059,6 @@ var ts; } var seenUsages = ts.createMap(); var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; - var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range; var inGenericContext = isInGenericContext(unmodifiedNode); collectUsages(target); @@ -93135,6 +94096,14 @@ var ts; // copy allTypeParameterUsages into all remaining scopes. ts.Debug.assert(i_1 === scopes.length); } + // If there are any declarations in the extracted block that are used in the same enclosing + // lexical scope, we can't move the extraction "up" as those declarations will become unreachable + if (visibleDeclarationsInExtractedRange.length) { + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) + ? scopes[0] + : ts.getEnclosingBlockScopeContainer(scopes[0]); + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } var _loop_8 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. @@ -93156,8 +94125,10 @@ var ts; } } }); - if (hasWrite && !isReadonlyArray(targetRange.range) && ts.isExpression(targetRange.range)) { - var diag = ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns); + // If an expression was extracted, then there shouldn't have been any variable declarations. + ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + var diag = ts.createDiagnosticForNode(targetRange.range, Messages.CannotWriteInExpression); functionErrorsPerScope[i].push(diag); constantErrorsPerScope[i].push(diag); } @@ -93166,16 +94137,16 @@ var ts; functionErrorsPerScope[i].push(diag); constantErrorsPerScope[i].push(diag); } + else if (firstExposedNonVariableDeclaration) { + var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.CannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } }; for (var i = 0; i < scopes.length; i++) { _loop_8(i); } - // If there are any declarations in the extracted block that are used in the same enclosing - // lexical scope, we can't move the extraction "up" as those declarations will become unreachable - if (visibleDeclarationsInExtractedRange.length) { - ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); - } - return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope }; + return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function hasTypeParameters(node) { return ts.isDeclarationWithTypeParameters(node) && node.typeParameters !== undefined && @@ -93209,7 +94180,7 @@ var ts; recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { - visibleDeclarationsInExtractedRange.push(node.symbol); + visibleDeclarationsInExtractedRange.push(node); } if (ts.isAssignmentExpression(node)) { // use 'write' as default usage for values @@ -93252,11 +94223,7 @@ var ts; } } function recordUsagebySymbol(identifier, usage, isTypeName) { - // If the identifier is both a property name and its value, we're only interested in its value - // (since the name is a declaration and will be included in the extracted range). - var symbol = identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier - ? checker.getShorthandAssignmentValueSymbol(identifier.parent) - : checker.getSymbolAtLocation(identifier); + var symbol = getSymbolReferencedByIdentifier(identifier); if (!symbol) { // cannot find symbol - do nothing return undefined; @@ -93340,37 +94307,52 @@ var ts; return; } // Otherwise check and recurse. - var sym = checker.getSymbolAtLocation(node); - if (sym && visibleDeclarationsInExtractedRange.some(function (d) { return d === sym; })) { - var diag = ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity); - for (var _i = 0, functionErrorsPerScope_2 = functionErrorsPerScope; _i < functionErrorsPerScope_2.length; _i++) { - var errors = functionErrorsPerScope_2[_i]; - errors.push(diag); + var sym = ts.isIdentifier(node) + ? getSymbolReferencedByIdentifier(node) + : checker.getSymbolAtLocation(node); + if (sym) { + var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; }); + if (decl) { + if (ts.isVariableDeclaration(decl)) { + var idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } + else { + // CONSIDER: this includes binding elements, which we could + // expose in the same way as variables. + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } } - for (var _a = 0, constantErrorsPerScope_2 = constantErrorsPerScope; _a < constantErrorsPerScope_2.length; _a++) { - var errors = constantErrorsPerScope_2[_a]; - errors.push(diag); - } - return true; - } - else { - ts.forEachChild(node, checkForUsedDeclarations); } + ts.forEachChild(node, checkForUsedDeclarations); + } + /** + * Return the symbol referenced by an identifier (even if it declares a different symbol). + */ + function getSymbolReferencedByIdentifier(identifier) { + // If the identifier is both a property name and its value, we're only interested in its value + // (since the name is a declaration and will be included in the extracted range). + return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); } function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { if (!symbol) { return undefined; } if (symbol.getDeclarations().some(function (d) { return d.parent === scopeDecl; })) { - return function () { return ts.createIdentifier(symbol.name); }; + return ts.createIdentifier(symbol.name); } var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode); if (prefix === undefined) { return undefined; } return isTypeNode - ? function () { return ts.createQualifiedName(prefix(), ts.createIdentifier(symbol.name)); } - : function () { return ts.createPropertyAccess(prefix(), symbol.name); }; + ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) + : ts.createPropertyAccess(prefix, symbol.name); } } function getParentNodeInSpan(node, file, span) { @@ -95006,7 +95988,7 @@ var ts; } function isNodeModulesFile(path) { var node_modulesFolderName = "/node_modules/"; - return path.indexOf(node_modulesFolderName) !== -1; + return ts.stringContains(path, node_modulesFolderName); } } function getRenameInfo(fileName, position) { @@ -96715,13 +97697,7 @@ var ts; * @param fileContent is a version of the file content that is known to be more up to date than the one on disk */ Session.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { - var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - if (this.eventHandler) { - this.eventHandler({ - eventName: "configFileDiag", - data: { triggerFile: fileName, configFileName: configFileName, diagnostics: configFileErrors || server.emptyArray } - }); - } + this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath); }; Session.prototype.getPosition = function (args, scriptInfo) { return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); @@ -97278,7 +98254,7 @@ var ts; return; } // No need to analyze lib.d.ts - var fileNamesInProject = fileNames.filter(function (value) { return value.indexOf("lib.d.ts") < 0; }); + var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); }); if (fileNamesInProject.length === 0) { return; } @@ -98586,18 +99562,28 @@ var ts; ts.addFileWatcher = addFileWatcher; function addFileWatcherWithLogging(host, file, cb, log) { var watcherCaption = "FileWatcher:: "; - return createWatcherWithLogging(addFileWatcher, watcherCaption, log, host, file, cb); + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, file, cb); } ts.addFileWatcherWithLogging = addFileWatcherWithLogging; + function addFileWatcherWithOnlyTriggerLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, file, cb); + } + ts.addFileWatcherWithOnlyTriggerLogging = addFileWatcherWithOnlyTriggerLogging; function addFilePathWatcher(host, file, cb, path) { return host.watchFile(file, function (fileName, eventKind) { return cb(fileName, eventKind, path); }); } ts.addFilePathWatcher = addFilePathWatcher; function addFilePathWatcherWithLogging(host, file, cb, path, log) { var watcherCaption = "FileWatcher:: "; - return createWatcherWithLogging(addFileWatcher, watcherCaption, log, host, file, cb, path); + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, file, cb, path); } ts.addFilePathWatcherWithLogging = addFilePathWatcherWithLogging; + function addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, file, cb, path); + } + ts.addFilePathWatcherWithOnlyTriggerLogging = addFilePathWatcherWithOnlyTriggerLogging; function addDirectoryWatcher(host, directory, cb, flags) { var recursive = (flags & 1 /* Recursive */) !== 0; return host.watchDirectory(directory, cb, recursive); @@ -98605,12 +99591,19 @@ var ts; ts.addDirectoryWatcher = addDirectoryWatcher; function addDirectoryWatcherWithLogging(host, directory, cb, flags, log) { var watcherCaption = "DirectoryWatcher " + ((flags & 1 /* Recursive */) !== 0 ? "recursive" : "") + ":: "; - return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, host, directory, cb, flags); + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, directory, cb, flags); } ts.addDirectoryWatcherWithLogging = addDirectoryWatcherWithLogging; - function createWatcherWithLogging(addWatch, watcherCaption, log, host, file, cb, optional) { + function addDirectoryWatcherWithOnlyTriggerLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1 /* Recursive */) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithOnlyTriggerLogging = addDirectoryWatcherWithOnlyTriggerLogging; + function createWatcherWithLogging(addWatch, watcherCaption, log, logOnlyTrigger, host, file, cb, optional) { var info = "PathInfo: " + file; - log(watcherCaption + "Added: " + info); + if (!logOnlyTrigger) { + log(watcherCaption + "Added: " + info); + } var watcher = addWatch(host, file, function (fileName, cbOptional1) { var optionalInfo = cbOptional1 !== undefined ? " " + cbOptional1 : ""; log(watcherCaption + "Trigger: " + fileName + optionalInfo + " " + info); @@ -98621,7 +99614,9 @@ var ts; }, optional); return { close: function () { - log(watcherCaption + "Close: " + info); + if (!logOnlyTrigger) { + log(watcherCaption + "Close: " + info); + } watcher.close(); } }; @@ -98670,7 +99665,9 @@ var ts; return { startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, - startCachingPerDirectoryResolution: startCachingPerDirectoryResolution, + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, @@ -98700,7 +99697,9 @@ var ts; resolvedModuleNames.clear(); resolvedTypeReferenceDirectives.clear(); allFilesHaveInvalidatedResolution = false; - ts.Debug.assert(perDirectoryResolvedModuleNames.size === 0 && perDirectoryResolvedTypeReferenceDirectives.size === 0); + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + clearPerDirectoryResolutions(); } function startRecordingFilesWithChangedResolutions() { filesWithChangedSetOfUnresolvedImports = []; @@ -98720,8 +99719,9 @@ var ts; filesWithInvalidatedResolutions = undefined; return function (path) { return collected && collected.has(path); }; } - function startCachingPerDirectoryResolution() { - ts.Debug.assert(perDirectoryResolvedModuleNames.size === 0 && perDirectoryResolvedTypeReferenceDirectives.size === 0); + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); } function finishCachingPerDirectoryResolution() { allFilesHaveInvalidatedResolution = false; @@ -98731,8 +99731,7 @@ var ts; watcher.watcher.close(); } }); - perDirectoryResolvedModuleNames.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); @@ -98844,18 +99843,15 @@ var ts; } var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); var dirPath = ts.getDirectoryPath(failedLookupLocationPath); + // If directory path contains node module, get the most parent node_modules directory for watching + while (ts.stringContains(dirPath, "/node_modules/")) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } // If the directory is node_modules use it to watch if (isNodeModulesDirectory(dirPath)) { return { dir: dir, dirPath: dirPath }; } - // If directory path contains node module, get the node_modules directory for watching - if (dirPath.indexOf("/node_modules/") !== -1) { - while (!isNodeModulesDirectory(dirPath)) { - dir = ts.getDirectoryPath(dir); - dirPath = ts.getDirectoryPath(dirPath); - } - return { dir: dir, dirPath: dirPath }; - } // Use some ancestor of the root directory if (rootPath !== undefined) { while (!isInDirectoryPath(dirPath, rootPath)) { @@ -99284,7 +100280,7 @@ var ts; /*@internal*/ function Project( /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, - /*@internal*/ directoryStructureHost, rootDirectoryForResolution) { + /*@internal*/ directoryStructureHost, currentDirectory) { this.projectName = projectName; this.projectKind = projectKind; this.projectService = projectService; @@ -99314,6 +100310,7 @@ var ts; this.projectStateVersion = 0; /*@internal*/ this.hasChangedAutomaticTypeDirectiveNames = false; + this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || ""); this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); if (!this.compilerOptions) { this.compilerOptions = ts.getDefaultCompilerOptions(); @@ -99332,8 +100329,9 @@ var ts; if (host.realpath) { this.realpath = function (path) { return host.realpath(path); }; } + // Use the current directory as resolution root only if the project created using current directory string + this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory); this.languageService = ts.createLanguageService(this, this.documentRegistry); - this.resolutionCache = ts.createResolutionCache(this, rootDirectoryForResolution); if (!languageServiceEnabled) { this.disableLanguageService(); } @@ -99415,10 +100413,10 @@ var ts; return this.cancellationToken; }; Project.prototype.getCurrentDirectory = function () { - return this.directoryStructureHost.getCurrentDirectory(); + return this.currentDirectory; }; Project.prototype.getDefaultLibFileName = function () { - var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.projectService.host.getExecutingFilePath())); + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.projectService.getExecutingFilePath())); return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilerOptions)); }; Project.prototype.useCaseSensitiveFileNames = function () { @@ -99530,10 +100528,9 @@ var ts; this.ensureBuilder(); var _a = this.builder.emitFile(this.program, scriptInfo.path), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; if (!emitSkipped) { - var projectRootPath = this.getProjectRootPath(); for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { var outputFile = outputFiles_1[_i]; - var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName)); + var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, this.currentDirectory); writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); } } @@ -99568,28 +100565,26 @@ var ts; return this.program.getSourceFileByPath(path); }; Project.prototype.close = function () { + var _this = this; if (this.program) { - // if we have a program - release all files that are enlisted in program + // if we have a program - release all files that are enlisted in program but arent root + // The releasing of the roots happens later + // The project could have pending update remaining and hence the info could be in the files but not in program graph for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { var f = _a[_i]; - var info = this.projectService.getScriptInfo(f.fileName); - // We might not find the script info in case its not associated with the project any more - // and project graph was not updated (eg delayed update graph in case of files changed/deleted on the disk) - if (info) { - info.detachFromProject(this); - } + this.detachScriptInfoIfNotRoot(f.fileName); } } - if (!this.program || !this.languageServiceEnabled) { - // release all root files either if there is no program or language service is disabled. - // in the latter case set of root files can be larger than the set of files in program. - for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { - var root = _c[_b]; - root.detachFromProject(this); - } + // Release external files + ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); }); + // Always remove root files from the project + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; + root.detachFromProject(this); } this.rootFiles = undefined; this.rootFilesMap = undefined; + this.externalFiles = undefined; this.program = undefined; this.builder = undefined; this.resolutionCache.clear(); @@ -99605,6 +100600,14 @@ var ts; this.languageService.dispose(); this.languageService = undefined; }; + Project.prototype.detachScriptInfoIfNotRoot = function (uncheckedFilename) { + var info = this.projectService.getScriptInfo(uncheckedFilename); + // We might not find the script info in case its not associated with the project any more + // and project graph was not updated (eg delayed update graph in case of files changed/deleted on the disk) + if (info && !this.isRoot(info)) { + info.detachFromProject(this); + } + }; Project.prototype.isClosed = function () { return this.rootFiles === undefined; }; @@ -99630,7 +100633,7 @@ var ts; return ts.map(this.program.getSourceFiles(), function (sourceFile) { var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); if (!scriptInfo) { - ts.Debug.fail("scriptInfo for a file '" + sourceFile.fileName + "' is missing."); + ts.Debug.fail("scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' is missing."); } return scriptInfo; }); @@ -99787,7 +100790,6 @@ var ts; */ Project.prototype.updateGraph = function () { this.resolutionCache.startRecordingFilesWithChangedResolutions(); - this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution(); var hasChanges = this.updateGraphWorker(); var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray; for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) { @@ -99842,8 +100844,10 @@ var ts; Project.prototype.updateGraphWorker = function () { var _this = this; var oldProgram = this.program; + ts.Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); this.writeLog("Starting updateGraphWorker: Project: " + this.getProjectName()); var start = ts.timestamp(); + this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution(); this.resolutionCache.startCachingPerDirectoryResolution(); this.program = this.languageService.getProgram(); this.resolutionCache.finishCachingPerDirectoryResolution(); @@ -100025,13 +101029,13 @@ var ts; var InferredProject = /** @class */ (function (_super) { __extends(InferredProject, _super); /*@internal*/ - function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, rootDirectoryForResolution) { + function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory) { var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, /*files*/ undefined, /*languageServiceEnabled*/ true, compilerOptions, - /*compileOnSaveEnabled*/ false, projectService.host, rootDirectoryForResolution) || this; - _this.projectRootPath = projectRootPath; + /*compileOnSaveEnabled*/ false, projectService.host, currentDirectory) || this; _this._isJsInferredProject = false; + _this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -100078,11 +101082,6 @@ var ts; return (!this.projectRootPath && !this.projectService.useSingleInferredProject) || this.getRootScriptInfos().length === 1; }; - InferredProject.prototype.getProjectRootPath = function () { - return this.projectRootPath || - // Single inferred project does not have a project root. - !this.projectService.useSingleInferredProject && ts.getDirectoryPath(this.getRootFiles()[0]); - }; InferredProject.prototype.close = function () { var _this = this; ts.forEach(this.getRootScriptInfos(), function (info) { return _this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); }); @@ -100152,7 +101151,7 @@ var ts; } // Search our peer node_modules, then any globally-specified probe paths // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ - var searchPaths = [ts.combinePaths(host.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.allowLocalPluginLoads) { var local = ts.getDirectoryPath(this.canonicalConfigFilePath); this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths"); @@ -100231,20 +101230,17 @@ var ts; this.projectService.logger.info("Plugin activation failed: " + e); } }; - ConfiguredProject.prototype.getProjectRootPath = function () { - return ts.getDirectoryPath(this.getConfigFilePath()); - }; /** * Get the errors that dont have any file name associated */ ConfiguredProject.prototype.getGlobalProjectErrors = function () { - return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }); + return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray; }; /** * Get all the project errors */ ConfiguredProject.prototype.getAllProjectErrors = function () { - return this.projectErrors; + return this.projectErrors || server.emptyArray; }; ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { this.projectErrors = projectErrors; @@ -100286,12 +101282,14 @@ var ts; } }; ConfiguredProject.prototype.close = function () { - _super.prototype.close.call(this); if (this.configFileWatcher) { this.configFileWatcher.close(); this.configFileWatcher = undefined; } this.stopWatchingWildCards(); + this.projectErrors = undefined; + this.configFileSpecs = undefined; + _super.prototype.close.call(this); }; ConfiguredProject.prototype.addOpenRef = function () { this.openRefCount++; @@ -100330,22 +101328,12 @@ var ts; /*hasExplicitListOfFiles*/ true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, projectService.host, ts.getDirectoryPath(projectFilePath || ts.normalizeSlashes(externalProjectName))) || this; _this.externalProjectName = externalProjectName; _this.compileOnSaveEnabled = compileOnSaveEnabled; - _this.projectFilePath = projectFilePath; _this.excludedFiles = []; return _this; } ExternalProject.prototype.getExcludedFiles = function () { return this.excludedFiles; }; - ExternalProject.prototype.getProjectRootPath = function () { - if (this.projectFilePath) { - return ts.getDirectoryPath(this.projectFilePath); - } - // if the projectFilePath is not given, we make the assumption that the project name - // is the path of the project file. AS the project name is provided by VS, we need to - // normalize slashes before using it as a file name. - return ts.getDirectoryPath(ts.normalizeSlashes(this.getProjectName())); - }; ExternalProject.prototype.getTypeAcquisition = function () { return this.typeAcquisition; }; @@ -100601,7 +101589,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.host.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); this.currentDirectory = this.host.getCurrentDirectory(); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); @@ -100622,6 +101610,11 @@ var ts; this.watchFilePath = function (host, file, cb, path, watchType, project) { return ts.addFilePathWatcherWithLogging(host, file, cb, path, _this.createWatcherLog(watchType, project)); }; this.watchDirectory = function (host, dir, cb, flags, watchType, project) { return ts.addDirectoryWatcherWithLogging(host, dir, cb, flags, _this.createWatcherLog(watchType, project)); }; } + else if (this.logger.loggingEnabled()) { + this.watchFile = function (host, file, cb, watchType, project) { return ts.addFileWatcherWithOnlyTriggerLogging(host, file, cb, _this.createWatcherLog(watchType, project)); }; + this.watchFilePath = function (host, file, cb, path, watchType, project) { return ts.addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, _this.createWatcherLog(watchType, project)); }; + this.watchDirectory = function (host, dir, cb, flags, watchType, project) { return ts.addDirectoryWatcherWithOnlyTriggerLogging(host, dir, cb, flags, _this.createWatcherLog(watchType, project)); }; + } else { this.watchFile = ts.addFileWatcher; this.watchFilePath = ts.addFilePathWatcher; @@ -100636,6 +101629,14 @@ var ts; ProjectService.prototype.toPath = function (fileName) { return ts.toPath(fileName, this.currentDirectory, this.toCanonicalFileName); }; + /*@internal*/ + ProjectService.prototype.getExecutingFilePath = function () { + return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath()); + }; + /*@internal*/ + ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) { + return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); + }; /* @internal */ ProjectService.prototype.getChangedFiles_TestOnly = function () { return this.changedFiles; @@ -100754,8 +101755,9 @@ var ts; // always set 'allowNonTsExtensions' for inferred projects since user cannot configure it from the outside // previously we did not expose a way for user to change these settings and this option was enabled by default compilerOptions.allowNonTsExtensions = true; - if (projectRootPath) { - this.compilerOptionsForInferredProjectsPerProjectRoot.set(projectRootPath, compilerOptions); + var canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath); + if (canonicalProjectRootPath) { + this.compilerOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, compilerOptions); } else { this.compilerOptionsForInferredProjects = compilerOptions; @@ -100771,8 +101773,8 @@ var ts; // root path // - Inferred projects with a projectRootPath, if the new options apply to that // project root path. - if (projectRootPath ? - project.projectRootPath === projectRootPath : + if (canonicalProjectRootPath ? + project.projectRootPath === canonicalProjectRootPath : !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) { project.setCompilerOptions(compilerOptions); project.compileOnSaveEnabled = compilerOptions.compileOnSave; @@ -100976,6 +101978,9 @@ var ts; ProjectService.prototype.removeProject = function (project) { this.logger.info("remove project: " + project.getRootFiles().toString()); project.close(); + if (ts.Debug.shouldAssert(1 /* Normal */)) { + this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project)); }); + } // Remove the project from pending project updates this.pendingProjectUpdates.delete(project.getProjectName()); switch (project.projectKind) { @@ -101309,7 +102314,7 @@ var ts; */ ProjectService.prototype.forEachConfigFileLocation = function (info, action, projectRootPath) { var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName)); - while (!projectRootPath || searchPath.indexOf(projectRootPath) >= 0) { + while (!projectRootPath || ts.containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames)) { var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); var result = action(tsconfigFileName, ts.combinePaths(canonicalSearchPath, "tsconfig.json")); @@ -101609,12 +102614,15 @@ var ts; project.watchWildcards(projectOptions.wildcardDirectories); } this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); + this.sendConfigFileDiagEvent(project, configFileName); + }; + ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { if (!this.eventHandler) { return; } this.eventHandler({ eventName: server.ConfigFileDiagEvent, - data: { configFileName: configFileName, diagnostics: project.getGlobalProjectErrors() || [], triggerFile: configFileName } + data: { configFileName: project.getConfigFilePath(), diagnostics: project.getAllProjectErrors(), triggerFile: triggerFile } }); }; ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (info, projectRootPath) { @@ -101622,10 +102630,11 @@ var ts; return undefined; } if (projectRootPath) { + var canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath); // if we have an explicit project root path, find (or create) the matching inferred project. for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var project = _a[_i]; - if (project.projectRootPath === projectRootPath) { + if (project.projectRootPath === canonicalProjectRootPath) { return project; } } @@ -101665,11 +102674,12 @@ var ts; if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === undefined) { return this.inferredProjects[0]; } - return this.createInferredProject(/*rootDirectoryForResolution*/ undefined, /*isSingleInferredProject*/ true); + // Single inferred project does not have a project root and hence no current directory + return this.createInferredProject(/*currentDirectory*/ undefined, /*isSingleInferredProject*/ true); }; - ProjectService.prototype.createInferredProject = function (rootDirectoryForResolution, isSingleInferredProject, projectRootPath) { + ProjectService.prototype.createInferredProject = function (currentDirectory, isSingleInferredProject, projectRootPath) { var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; - var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, rootDirectoryForResolution); + var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory); if (isSingleInferredProject) { this.inferredProjects.unshift(project); } @@ -101905,6 +102915,7 @@ var ts; ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { var _this = this; var configFileName; + var sendConfigFileDiagEvent = false; var configFileErrors; var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, fileContent, scriptKind, hasMixedContent); var project = this.findContainingExternalProject(fileName); @@ -101914,13 +102925,8 @@ var ts; project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { project = this.createConfiguredProject(configFileName); - // even if opening config file was successful, it could still - // contain errors that were tolerated. - var errors = project.getGlobalProjectErrors(); - if (errors && errors.length > 0) { - // set configFileErrors only when the errors array is non-empty - configFileErrors = errors; - } + // Send the event only if the project got created as part of this open request + sendConfigFileDiagEvent = true; } } } @@ -101933,9 +102939,16 @@ var ts; // At this point if file is part of any any configured or external project, then it would be present in the containing projects // So if it still doesnt have any containing projects, it needs to be part of inferred project if (info.isOrphan()) { + // Since the file isnt part of configured project, do not send config file event + configFileName = undefined; + sendConfigFileDiagEvent = false; this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); } this.addToListOfOpenFiles(info); + if (sendConfigFileDiagEvent) { + configFileErrors = project.getAllProjectErrors(); + this.sendConfigFileDiagEvent(project, fileName); + } // Remove the configured projects that have zero references from open files. // This was postponed from closeOpenFile to after opening next file, // so that we can reuse the project if we need to right away diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index d41db2eb413..14fae7d0d77 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -1442,6 +1442,10 @@ declare namespace ts { interface JSDocUnknownTag extends JSDocTag { kind: SyntaxKind.JSDocTag; } + /** + * Note that `@extends` is a synonym of `@augments`. + * Both tags are represented by this interface. + */ interface JSDocAugmentsTag extends JSDocTag { kind: SyntaxKind.JSDocAugmentsTag; class: ExpressionWithTypeArguments & { @@ -1473,7 +1477,7 @@ declare namespace ts { interface JSDocPropertyLikeTag extends JSDocTag, Declaration { parent: JSDoc; name: EntityName; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ isNameFirst: boolean; isBracketed: boolean; @@ -1727,6 +1731,10 @@ declare namespace ts { signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + /** + * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead + * This will be removed in a future version. + */ getSymbolDisplayBuilder(): SymbolDisplayBuilder; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; @@ -2921,6 +2929,8 @@ declare namespace ts { function getJSDocReturnType(node: Node): TypeNode | undefined; /** Get all JSDoc tags related to a node, including those on parent nodes. */ function getJSDocTags(node: Node): ReadonlyArray | undefined; + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray | undefined; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -3113,6 +3123,8 @@ declare namespace ts { function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node: Node): boolean; + function isSetAccessor(node: Node): node is SetAccessorDeclaration; + function isGetAccessor(node: Node): node is GetAccessorDeclaration; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; diff --git a/lib/typescript.js b/lib/typescript.js index 3ea6fca626e..ca24c94ce30 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -1363,7 +1363,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.6"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -1542,10 +1542,12 @@ var ts; } ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { + var result = []; Debug.assert(arrayA.length === arrayB.length); for (var i = 0; i < arrayA.length; i++) { - callback(arrayA[i], arrayB[i], i); + result.push(callback(arrayA[i], arrayB[i], i)); } + return result; } ts.zipWith = zipWith; function zipToMap(keys, values) { @@ -1674,22 +1676,6 @@ var ts; return array; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var item = array_2[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var i = 0; i < array.length; i++) { @@ -1745,8 +1731,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1927,8 +1913,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (predicate(v)) { return true; } @@ -1954,8 +1940,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + loop: for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -2048,8 +2034,8 @@ var ts; ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; // Note: we need the following type assertion because of GH #17069 result += v[prop]; } @@ -2422,8 +2408,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; @@ -2864,7 +2850,7 @@ var ts; } ts.getDirectoryPath = getDirectoryPath; function isUrl(path) { - return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + return path && !isRootedDiskPath(path) && stringContains(path, "://"); } ts.isUrl = isUrl; function pathIsRelative(path) { @@ -3120,8 +3106,12 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; function hasExtension(fileName) { - return getBaseFileName(fileName).indexOf(".") >= 0; + return stringContains(getBaseFileName(fileName), "."); } ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { @@ -4686,6 +4676,7 @@ var ts; Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), 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."), @@ -5013,6 +5004,7 @@ var ts; A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), 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}'."), @@ -5336,9 +5328,10 @@ var ts; Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), - JSDoc_augments_is_not_attached_to_a_class_declaration: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_augments_is_not_attached_to_a_class_declaration_8022", "JSDoc '@augments' is not attached to a class declaration."), - JSDoc_augments_0_does_not_match_the_extends_1_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023", "JSDoc '@augments {0}' does not match the 'extends {1}' clause."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), 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."), @@ -5370,7 +5363,7 @@ 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(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), - Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'."), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), @@ -5384,6 +5377,7 @@ var ts; Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'."), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), @@ -5392,6 +5386,8 @@ var ts; Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Infer_type_of_0_from_usage: diag(95009, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95009", "Infer type of '{0}' from usage."), + Infer_parameter_types_from_usage: diag(95010, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95010", "Infer parameter types from usage."), }; })(ts || (ts = {})); /// @@ -8707,27 +8703,14 @@ var ts; } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { - return isRestParameter(ts.lastOrUndefined(s.parameters)); + var last = ts.lastOrUndefined(s.parameters); + return last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; - function hasDeclaredRestParameter(s) { - return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); - } - ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 274 /* JSDocVariadicType */ || - ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274 /* JSDocVariadicType */; })) { - return true; - } - } - return isDeclaredRestParam(node); + return node.dotDotDotToken !== undefined; } ts.isRestParameter = isRestParameter; - function isDeclaredRestParam(node) { - return node && node.dotDotDotToken !== undefined; - } - ts.isDeclaredRestParam = isDeclaredRestParam; var AssignmentKind; (function (AssignmentKind) { AssignmentKind[AssignmentKind["None"] = 0] = "None"; @@ -11010,27 +10993,35 @@ var ts; if (!declaration) { return undefined; } - if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143 /* QualifiedName */) { - return declaration.name.right; - } - if (declaration.kind === 194 /* BinaryExpression */) { - var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { - case 1 /* ExportsProperty */: - case 4 /* ThisProperty */: - case 5 /* Property */: - case 3 /* PrototypeProperty */: - return expr.left.name; - default: - return undefined; + switch (declaration.kind) { + case 284 /* JSDocPropertyTag */: + case 279 /* JSDocParameterTag */: { + var name = declaration.name; + if (name.kind === 143 /* QualifiedName */) { + return name.right; + } + break; + } + case 194 /* BinaryExpression */: { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + default: + return undefined; + } + } + case 283 /* JSDocTypedefTag */: + return getNameOfJSDocTypedef(declaration); + case 243 /* ExportAssignment */: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; } } - else if (declaration.kind === 283 /* JSDocTypedefTag */) { - return getNameOfJSDocTypedef(declaration); - } - else { - return declaration.name; - } + return declaration.name; } ts.getNameOfDeclaration = getNameOfDeclaration; /** @@ -11143,6 +11134,12 @@ var ts; var tags = getJSDocTags(node); return ts.find(tags, function (doc) { return doc.kind === kind; }); } + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node, kind) { + var tags = getJSDocTags(node); + return ts.filter(tags, function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -12493,6 +12490,14 @@ var ts; return node.kind >= 276 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 154 /* SetAccessor */; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 153 /* GetAccessor */; + } + ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ /* @internal */ function hasJSDocNodes(node) { @@ -18161,6 +18166,7 @@ var ts; if (tagName) { switch (tagName.escapedText) { case "augments": + case "extends": tag = parseAugmentsTag(atToken, tagName); break; case "class": @@ -18456,7 +18462,7 @@ var ts; if (typeExpression && typeExpression.type.kind === 164 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); } @@ -18732,8 +18738,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var node = array_7[_i]; visitNode(node); } } @@ -18870,8 +18876,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } return; @@ -19219,6 +19225,14 @@ var ts; // state used to aggregate transform flags during bind. var subtreeTransformFlags = 0 /* None */; var skipTransformFlagAggregation; + /** + * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) + * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) + * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. + */ + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } function bindSourceFile(f, opts) { file = f; options = opts; @@ -19293,6 +19307,9 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { + if (node.kind === 243 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } var name = ts.getNameOfDeclaration(node); if (name) { if (ts.isAmbientModule(node)) { @@ -19323,8 +19340,6 @@ var ts; return "__index" /* Index */; case 244 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 243 /* ExportAssignment */: - return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; case 194 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { // module.exports = ... @@ -19440,9 +19455,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } @@ -20175,7 +20190,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } if (!node.statement || node.statement.kind !== 212 /* DoStatement */) { // do statement sets current flow inside bindDoStatement @@ -20669,7 +20684,7 @@ var ts; !ts.isInAmbientContext(node)) { // Report error only if there are no parse errors in file if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); } } } @@ -20764,7 +20779,7 @@ var ts; } function checkStrictModeNumericLiteral(node) { if (inStrictMode && node.numericLiteralFlags & 4 /* Octal */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } function checkStrictModePostfixUnaryExpression(node) { @@ -21057,7 +21072,7 @@ var ts; // falls through case 284 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 272 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); @@ -21114,20 +21129,20 @@ var ts; } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } if (node.parent.kind !== 265 /* SourceFile */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { var parent_1 = node.parent; if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } } @@ -21166,15 +21181,12 @@ var ts; function isExportsOrModuleExportsOrAlias(node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); } function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (ts.isIdentifier(node)) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - return false; + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(node) { return isExportsOrModuleExportsOrAlias(node) || @@ -21238,17 +21250,19 @@ var ts; // follow the function declaration var leftSideOfAssignment = node.left; var target = leftSideOfAssignment.expression; - // Fix up parent pointers since we're going to use these nodes before we bind into them - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - // This can be an alias for the 'exports' or 'module.exports' names, e.g. - // var util = module.exports; - // util.property = function ... - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); + if (ts.isIdentifier(target)) { + // Fix up parent pointers since we're going to use these nodes before we bind into them + leftSideOfAssignment.parent = node; + target.parent = leftSideOfAssignment; + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); + } } } function lookupSymbolForName(name) { @@ -21304,7 +21318,7 @@ var ts; if (node.name) { node.name.parent = node; } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); } symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); prototypeSymbol.parent = symbol; @@ -21520,6 +21534,11 @@ var ts; } if (expression.kind === 91 /* ImportKeyword */) { transformFlags |= 67108864 /* 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 */; + } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; @@ -23316,7 +23335,7 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : withoutAtTypePrefix; } @@ -23610,6 +23629,23 @@ var ts; return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getBooleanType: function () { return booleanType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, isArrayLikeType: isArrayLikeType, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, @@ -23657,6 +23693,7 @@ var ts; anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var markerSuperType = createType(16384 /* TypeParameter */); var markerSubType = createType(16384 /* TypeParameter */); markerSubType.constraint = markerSuperType; @@ -23858,6 +23895,12 @@ var ts; CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; })(CheckMode || (CheckMode = {})); + var CallbackCheck; + (function (CallbackCheck) { + CallbackCheck[CallbackCheck["None"] = 0] = "None"; + CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; + CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; + })(CallbackCheck || (CallbackCheck = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); @@ -24226,6 +24269,7 @@ var ts; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; + var lastNonBlockLocation; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; @@ -24437,13 +24481,16 @@ var ts; } break; } + if (location.kind !== 207 /* Block */) { + lastNonBlockLocation = location; + } lastLocation = location; location = location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; } if (!result) { @@ -27162,13 +27209,13 @@ var ts; if (parentType === unknownType) { return unknownType; } - // If no type was specified or inferred for parent, or if the specified or inferred type is any, - // infer from the initializer of the binding element if one is present. Otherwise, go with the - // undefined or any type of the parent. - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } + // If no type was specified or inferred for parent, + // infer from the initializer of the binding element if one is present. + // Otherwise, go with the undefined type of the parent. + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { return parentType; } var type; @@ -27194,9 +27241,6 @@ var ts; // computed properties with non-literal names are treated as 'any' return anyType; } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } // 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. var text = ts.getTextOfPropertyName(name); @@ -28944,27 +28988,48 @@ var ts; function getApparentTypeOfIntersectionType(type) { return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); } + function getResolvedTypeParameterDefault(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + // To block recursion, set the initial value to the resolvingDefaultType. + typeParameter.default = resolvingDefaultType; + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + // If we have not been called recursively, set the correct default type. + typeParameter.default = defaultType; + } + } + } + else if (typeParameter.default === resolvingDefaultType) { + // If we are called recursively for this type parameter, mark the default as circular. + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } /** * Gets the default type for a type parameter. * * If the type parameter is the result of an instantiation, this gets the instantiated - * default type of its target. If the type parameter has no default type, `undefined` - * is returned. - * - * This function *does not* perform a circularity check. + * default type of its target. If the type parameter has no default type or the default is + * circular, `undefined` is returned. */ function getDefaultFromTypeParameter(typeParameter) { - if (!typeParameter.default) { - if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); - typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; - } - else { - var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; - } - } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + /** + * Indicates whether the declaration of a typeParameter has a default type. + */ + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, @@ -29128,7 +29193,7 @@ var ts; return getIndexTypeOfStructuredType(getApparentType(type), kind); } function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { + if (isObjectTypeWithInferableIndex(type)) { var propTypes = []; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; @@ -29232,7 +29297,7 @@ var ts; var minTypeArgumentCount = 0; if (typeParameters) { for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { + if (!hasTypeParameterDefault(typeParameters[i])) { minTypeArgumentCount = i + 1; } } @@ -30572,7 +30637,7 @@ var ts; * this function should be called in a left folding style, with left = previous result of getSpreadType * and right = the new element to be spread. */ - function getSpreadType(left, right) { + function getSpreadType(left, right, symbol, propagatedFlags) { if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { return anyType; } @@ -30583,10 +30648,10 @@ var ts; return left; } if (left.flags & 65536 /* Union */) { - return mapType(left, function (t) { return getSpreadType(t, right); }); + return mapType(left, function (t) { return getSpreadType(t, right, symbol, propagatedFlags); }); } if (right.flags & 65536 /* Union */) { - return mapType(right, function (t) { return getSpreadType(left, t); }); + return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } if (right.flags & 16777216 /* NonPrimitive */) { return nonPrimitiveType; @@ -30643,7 +30708,12 @@ var ts; members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); } } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var spread = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + spread.flags |= propagatedFlags; + spread.flags |= 1048576 /* FreshLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */; + spread.symbol = symbol; + return spread; } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { @@ -30945,11 +31015,11 @@ var ts; // The first time an anonymous type is instantiated we compute and store a list of the type // parameters that are in scope (and therefore potentially referenced). For type literals that // aren't the right hand side of a generic type alias declaration we optimize by reducing the - // set of type parameters to those that are actually referenced somewhere in the literal. + // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true) || ts.emptyArray; typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? - ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : outerTypeParameters; links.typeParameters = typeParameters; if (typeParameters.length) { @@ -30974,13 +31044,27 @@ var ts; } return type; } - function isTypeParameterReferencedWithin(tp, node) { - return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); - function checkThis(node) { - return node.kind === 169 /* ThisType */ || ts.forEachChild(node, checkThis); + function isTypeParameterPossiblyReferenced(tp, node) { + // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks + // between the node and the type parameter declaration, if the node contains actual references to the + // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_1 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 207 /* Block */ ? "quit" : n === container_1; })) { + return ts.forEachChild(node, containsReference); + } } - function checkIdentifier(node) { - return node.kind === 71 /* Identifier */ && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + return true; + function containsReference(node) { + switch (node.kind) { + case 169 /* ThisType */: + return tp.isThisType; + case 71 /* Identifier */: + return !tp.isThisType && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp; + case 162 /* TypeQuery */: + return true; + } + return ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -31181,13 +31265,13 @@ var ts; return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, /*checkAsCallback*/ false, ignoreReturnTypes, /*reportErrors*/ false, + return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; } /** * See signatureRelatedTo, compareSignaturesIdentical */ - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; @@ -31200,7 +31284,7 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = strictFunctionTypes && kind !== 151 /* MethodDeclaration */ && + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 151 /* MethodDeclaration */ && kind !== 150 /* MethodSignature */ && kind !== 152 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); @@ -31227,21 +31311,21 @@ var ts; for (var i = 0; i < checkCount; i++) { var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); // 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 - // function types with a single call signature, we known we are relating two callback parameters. In + // function types with a single call signature, we know we are relating two callback parameters. In // that case it is sufficient to only relate the parameters of the signatures co-variantly because, // similar to return values, callback parameters are output positions. This means that a Promise, // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) // with respect to T. + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && (getFalsyFlags(sourceType) & 6144 /* Nullable */) === (getFalsyFlags(targetType) & 6144 /* Nullable */); var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, /*checkAsCallback*/ true, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.symbolName(sourceParams[i < sourceMax ? i : sourceMax]), ts.symbolName(targetParams[i < targetMax ? i : targetMax])); @@ -31272,7 +31356,7 @@ var ts; // When relating callback signatures, we still need to relate return types bi-variantly as otherwise // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } // wouldn't be co-variant for T without this rule. - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || + result &= callbackCheck === 1 /* Bivariant */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || compareTypes(sourceReturnType, targetReturnType, reportErrors); } } @@ -31682,6 +31766,13 @@ var ts; (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } + if (target.flags & 65536 /* Union */) { + var discriminantType = findMatchingDiscriminantType(source, target); + if (discriminantType) { + // check excess properties against discriminant type only, not the entire union + return hasExcessProperties(source, discriminantType, reportErrors); + } + } var _loop_4 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -31758,22 +31849,25 @@ var ts; return 0 /* False */; } function findMatchingDiscriminantType(source, target) { + var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.escapedName)) { - 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)) { - return type; + var sourceProperty = findSingleDiscriminantProperty(sourceProperties, target); + if (sourceProperty) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var type = _a[_i]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); + if (targetType && isRelatedTo(sourceType, targetType)) { + if (match) { + return undefined; } + match = type; } } } } + return match; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -32231,8 +32325,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); if (!targetProp) { return 0 /* False */; @@ -32320,8 +32414,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, - /*checkAsCallback*/ false, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -32382,7 +32475,7 @@ var ts; // if T is related to U. return kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); } - if (isObjectLiteralType(source)) { + if (isObjectTypeWithInferableIndex(source)) { var related = -1 /* True */; if (kind === 0 /* String */) { var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); @@ -32852,11 +32945,11 @@ var ts; return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; } /** - * Return true if type was inferred from an object literal or written as an object type literal + * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module * with no call or construct signatures. */ - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */)) !== 0 && + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 512 /* ValueModule */)) !== 0 && getSignaturesOfType(type, 0 /* Call */).length === 0 && getSignaturesOfType(type, 1 /* Construct */).length === 0; } @@ -33663,6 +33756,19 @@ var ts; } return false; } + function findSingleDiscriminantProperty(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + return undefined; + } + result = sourceProperty; + } + } + return result; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -36144,7 +36250,7 @@ var ts; checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -36156,7 +36262,7 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return unknownType; } - spread = getSpreadType(spread, type); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags); offset = i + 1; continue; } @@ -36198,14 +36304,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768 /* Object */) { - // only set the symbol and flags if this is a (fresh) object type - spread.flags |= propagatedFlags; - spread.flags |= 1048576 /* FreshLiteral */; - spread.objectFlags |= 128 /* ObjectLiteral */; - spread.symbol = node.symbol; + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); } return spread; } @@ -36256,7 +36355,7 @@ var ts; */ function isUnhyphenatedJsxName(name) { // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers - return name.indexOf("-") < 0; + return !ts.stringContains(name, "-"); } /** * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name @@ -36315,7 +36414,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); attributesArray = []; attributesTable = ts.createSymbolTable(); } @@ -36324,7 +36423,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*propagatedFlags*/ 0); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -36334,7 +36433,7 @@ var ts; if (!hasSpreadAnyType) { if (spread !== emptyObjectType) { if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); } attributesArray = getPropertiesOfType(spread); } @@ -37707,29 +37806,27 @@ var ts; } return getInferredTypes(context); } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJavaScriptFile(signature.declaration); var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable /* so far */) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } + 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 && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + 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; } } - return typeArgumentsAreAssignable; + return typeArgumentTypes; } /** * Check if the given signature can possibly be a signature called by the JSX opening-like element. @@ -38207,8 +38304,7 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } else if (candidateForTypeArgumentError) { - var typeArguments_1 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -38258,14 +38354,14 @@ var ts; var candidate = candidates[bestIndex]; var typeParameters = candidate.typeParameters; if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_2 = node.typeArguments.map(getTypeOfNode); - while (typeArguments_2.length > typeParameters.length) { - typeArguments_2.pop(); + var typeArguments_1 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_1.length > typeParameters.length) { + typeArguments_1.pop(); } - while (typeArguments_2.length < typeParameters.length) { - typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + while (typeArguments_1.length < typeParameters.length) { + typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); } - var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + var instantiated = createSignatureInstantiation(candidate, typeArguments_1); candidates[bestIndex] = instantiated; return instantiated; } @@ -38300,10 +38396,12 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); - if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false)) { + var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (typeArgumentResult) { + typeArgumentTypes = typeArgumentResult; + } + else { candidateForTypeArgumentError = originalCandidate; break; } @@ -38311,6 +38409,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { @@ -38579,6 +38678,11 @@ var ts; if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; @@ -38589,6 +38693,18 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); } + /** + * Sometimes, we have a decorator that could accept zero arguments, + * but is receiving too many arguments as part of the decorator invocation. + * In those cases, a user may have meant to *call* the expression before using it as a decorator. + */ + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, 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 @@ -40272,6 +40388,9 @@ var ts; if (!hasNonCircularBaseConstraint(typeParameter)) { error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } var constraintType = getConstraintOfTypeParameter(typeParameter); var defaultType = getDefaultFromTypeParameter(typeParameter); if (constraintType && defaultType) { @@ -40291,7 +40410,6 @@ var ts; checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - func = ts.getContainingFunction(node); if (!(func.kind === 152 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } @@ -41648,17 +41766,22 @@ var ts; } } function checkJSDocAugmentsTag(node) { - var cls = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(cls) && !ts.isClassExpression(cls)) { - error(cls, ts.Diagnostics.JSDoc_augments_is_not_attached_to_a_class_declaration); + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } + var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 277 /* JSDocAugmentsTag */); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } var name = getIdentifierFromEntityNameExpression(node.class.expression); - var extend = ts.getClassExtendsHeritageClauseElement(cls); + var extend = ts.getClassExtendsHeritageClauseElement(classLike); if (extend) { var className = getIdentifierFromEntityNameExpression(extend.expression); if (className && name.escapedText !== className.escapedText) { - error(name, ts.Diagnostics.JSDoc_augments_0_does_not_match_the_extends_1_clause, ts.idText(name), ts.idText(className)); + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); } } } @@ -41908,7 +42031,7 @@ var ts; } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -46671,6 +46794,9 @@ var ts; // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). + if (node === undefined) { + return undefined; + } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; setOriginalNode(clone, node); @@ -48937,6 +49063,16 @@ var ts; return node; } ts.setEmitFlags = setEmitFlags; + /** + * Sets flags that control emit behavior of a node. + */ + /* @internal */ + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; /** * Gets a custom text range to use when emitting source maps. */ @@ -51733,6 +51869,19 @@ var ts; } return values; } + /** + * Used in the module transformer to check if an expression is reasonably without sideeffect, + * and thus better to copy into multiple places rather than to cache in a temporary variable + * - this is mostly subjective beyond the requirement that the expression not be sideeffecting + */ + function isSimpleCopiableExpression(expression) { + return expression.kind === 9 /* StringLiteral */ || + expression.kind === 8 /* NumericLiteral */ || + expression.kind === 13 /* NoSubstitutionTemplateLiteral */ || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; })(ts || (ts = {})); /// /// @@ -52204,7 +52353,7 @@ var ts; ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; - ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; + ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; @@ -52215,6 +52364,7 @@ var ts; var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = typeof compilerOptions.strictNullChecks === "undefined" ? compilerOptions.strict : compilerOptions.strictNullChecks; var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); // Save the previous transformation hooks. @@ -52646,8 +52796,9 @@ var ts; var facts = 0 /* None */; if (ts.some(staticProperties)) facts |= 1 /* HasStaticInitializedProperties */; - if (ts.getClassExtendsHeritageClauseElement(node)) - facts |= 64 /* HasExtendsClause */; + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) + facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) facts |= 2 /* HasConstructorDecorators */; if (ts.childIsDecorated(node)) @@ -52771,7 +52922,7 @@ var ts; : undefined; var classDeclaration = ts.createClassDeclaration( /*decorators*/ undefined, modifiers, name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0)); // To better align with the old emitter, we should not emit a trailing source map // entry if the class has static properties. var emitFlags = ts.getEmitFlags(node); @@ -52880,7 +53031,7 @@ var ts; // ${members} // } var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0); + var members = transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0); var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, location); @@ -52936,11 +53087,11 @@ var ts; * Transforms the members of a class. * * @param node The current class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformClassMembers(node, hasExtendsClause) { + function transformClassMembers(node, isDerivedClass) { var members = []; - var constructor = transformConstructor(node, hasExtendsClause); + var constructor = transformConstructor(node, isDerivedClass); if (constructor) { members.push(constructor); } @@ -52951,9 +53102,9 @@ var ts; * Transforms (or creates) a constructor for a class. * * @param node The current class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformConstructor(node, hasExtendsClause) { + function transformConstructor(node, isDerivedClass) { // 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 @@ -52966,7 +53117,7 @@ var ts; return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause); + var body = transformConstructorBody(node, constructor, isDerivedClass); // constructor(${parameters}) { // ${body} // } @@ -52979,7 +53130,6 @@ var ts; * parameter property assignments or instance property initializers. * * @param constructor The constructor declaration. - * @param hasExtendsClause A value indicating whether the class has an extends clause. */ function transformConstructorParameters(constructor) { // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: @@ -53006,9 +53156,9 @@ var ts; * * @param node The current class. * @param constructor The current class constructor. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformConstructorBody(node, constructor, hasExtendsClause) { + function transformConstructorBody(node, constructor, isDerivedClass) { var statements = []; var indexOfFirstStatement = 0; resumeLexicalEnvironment(); @@ -53029,7 +53179,7 @@ var ts; var propertyAssignments = getParametersWithPropertyAssignments(constructor); ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); } - else if (hasExtendsClause) { + else if (isDerivedClass) { // Add a synthetic `super` call: // // super(...arguments); @@ -53759,6 +53909,15 @@ var ts; var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 168 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 130 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 139 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } var serializedIndividual = serializeTypeNode(typeNode); if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { // One of the individual is global object, return immediately @@ -53778,7 +53937,7 @@ var ts; } } // If we were able to find common type, use it - return serializedUnion; + return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never } /** * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with @@ -60580,7 +60739,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { - if (ts.forEach(node.arguments, containsYield)) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { // [source] // a.b(1, yield, 2); // @@ -62333,7 +62492,7 @@ var ts; default: return transformCommonJSModule; } } - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -62688,17 +62847,19 @@ var ts; } } function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: - return transformImportCallExpressionAMD(node); + return createImportCallExpressionAMD(argument, containsLexicalThis); case ts.ModuleKind.UMD: - return transformImportCallExpressionUMD(node); + return createImportCallExpressionUMD(argument, containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return transformImportCallExpressionCommonJS(node); + return createImportCallExpressionCommonJS(argument, containsLexicalThis); } } - function transformImportCallExpressionUMD(node) { + function createImportCallExpressionUMD(arg, containsLexicalThis) { // (function (factory) { // ... (regular UMD) // } @@ -62713,12 +62874,22 @@ var ts; // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ // }); needUMDDynamicImportHelper = true; - return ts.createConditional( - /*condition*/ ts.createIdentifier("__syncRequire"), - /*whenTrue*/ transformImportCallExpressionCommonJS(node), - /*whenFalse*/ transformImportCallExpressionAMD(node)); + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */); + return ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); + } } - function transformImportCallExpressionAMD(node) { + function createImportCallExpressionAMD(arg, containsLexicalThis) { // improt("./blah") // emit as // define(["require", "exports", "blah"], function (require, exports) { @@ -62727,30 +62898,71 @@ var ts; // }); var resolve = ts.createUniqueName("resolve"); var reject = ts.createUniqueName("reject"); - return ts.createNew(ts.createIdentifier("Promise"), - /*typeArguments*/ undefined, [ts.createFunctionExpression( + var parameters = [ + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + ]; + var body = ts.createBlock([ + ts.createStatement(ts.createCall(ts.createIdentifier("require"), + /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, body); + } + else { + func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), - ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)], - /*type*/ undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), - /*typeArguments*/ undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); } - function transformImportCallExpressionCommonJS(node) { + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { // import("./blah") // emit as // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ // We have to wrap require in then callback so that require is done in asynchronously // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately - return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []), "then"), - /*typeArguments*/ undefined, [ts.createFunctionExpression( + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); + var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, requireCall); + } + else { + func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, - /*parameters*/ undefined, - /*type*/ undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, node.arguments))]))]); + /*parameters*/ [], + /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)])); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); } /** * Visits an ImportDeclaration node. @@ -62906,10 +63118,10 @@ var ts; if (original && hasAssociatedEndOfDeclarationMarker(original)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); } return ts.singleOrMany(statements); } @@ -64649,7 +64861,7 @@ var ts; // }; // }); return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), - /*typeArguments*/ undefined, node.arguments); + /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); } /** * Visits a DestructuringAssignment to flatten destructuring to exported symbols. @@ -66222,7 +66434,7 @@ var ts; }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); - return comment.indexOf("@internal") >= 0; + return ts.stringContains(comment, "@internal"); } function stripInternal(node) { if (node) { @@ -68866,7 +69078,7 @@ var ts; // check if numeric literal is a decimal literal that was originally written with a dot var text = getLiteralTextOfNode(expression); return !expression.numericLiteralFlags - && text.indexOf(ts.tokenToString(23 /* DotToken */)) < 0; + && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -70610,8 +70822,7 @@ var ts; existingInfo.version = sourceFile.version; emitHandler.onUpdateSourceFile(program, sourceFile); } - else if (program.hasInvalidatedResolution(sourceFile.path) && - emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { + else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { registerChangedFile(sourceFile.path, sourceFile.fileName); } } @@ -71496,8 +71707,7 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, - hasInvalidatedResolution: hasInvalidatedResolution + redirectTargetsSet: redirectTargetsSet }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -71869,10 +72079,17 @@ var ts; if (file.hasNoDefaultLib) { return true; } - if (defaultLibraryPath && defaultLibraryPath.length !== 0) { - return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, /*ignoreCase*/ !host.useCaseSensitiveFileNames()); + if (!options.noLib) { + return false; + } + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + if (!options.lib) { + return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + else { + return ts.forEach(options.lib, function (libFileName) { return ts.compareStrings(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; }); } - return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); @@ -76511,6 +76728,64 @@ var ts; return position; } ts.getSourceFileImportLocation = getSourceFileImportLocation; + /** + * Creates a deep, memberwise clone of a node with no source map location. + * + * WARNING: This is an expensive operation and is only intended to be used in refactorings + * and code fixes (because those are triggered by explicit user actions). + */ + function getSynthesizedDeepClone(node) { + if (node === undefined) { + return undefined; + } + var visited = 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; + } + else if (ts.isNumericLiteral(clone_7)) { + clone_7.numericLiteralFlags = node.numericLiteralFlags; + } + clone_7.pos = node.pos; + clone_7.end = node.end; + return clone_7; + } + // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update + // the new node created by visitEachChild with the extra changes getSynthesizedClone + // would have made. + visited.parent = undefined; + return visited; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + /** + * Sets EmitFlags to suppress leading and trailing trivia on the node. + */ + /* @internal */ + function suppressLeadingAndTrailingTrivia(node) { + ts.Debug.assert(node !== undefined); + suppressLeading(node); + suppressTrailing(node); + function suppressLeading(node) { + ts.addEmitFlags(node, 512 /* NoLeadingComments */); + var firstChild = ts.forEachChild(node, function (child) { return child; }); + firstChild && suppressLeading(firstChild); + } + function suppressTrailing(node) { + ts.addEmitFlags(node, 1024 /* NoTrailingComments */); + var lastChild = undefined; + ts.forEachChild(node, function (child) { return (lastChild = child, undefined); }, function (children) { + // As an optimization, jump straight to the end of the list. + if (children.length) { + lastChild = ts.last(children); + } + return undefined; + }); + lastChild && suppressTrailing(lastChild); + } + } + ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; })(ts || (ts = {})); var ts; (function (ts) { @@ -77574,7 +77849,7 @@ var ts; var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = fragment.indexOf(ts.directorySeparator) !== -1; + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); @@ -77606,7 +77881,7 @@ var ts; } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module - var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; + var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; // Get modules that the type checker picked up var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); @@ -78909,6 +79184,11 @@ var ts; if (ts.isClassLike(location)) { return location; } + // class c { method() { } b| } + if (isFromClassElementDeclaration(location) && + location.parent.name === location) { + return location.parent.parent; + } break; default: if (isFromClassElementDeclaration(contextToken) && @@ -80581,9 +80861,6 @@ var ts; return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { - if (ts.isExportAssignment(decl)) { - return ts.isIdentifier(decl.expression) ? decl.expression.escapedText : undefined; - } var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 /* Identifier */ && name.escapedText; }); @@ -81022,7 +81299,7 @@ var ts; State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(this.checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { @@ -85639,13 +85916,19 @@ var ts; } if (symbolFlags & 2097152 /* Alias */) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 236 /* NamespaceExportDeclaration */) { - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129 /* NamespaceKeyword */)); - } - else { - displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); + switch (symbol.declarations[0].kind) { + case 236 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(129 /* NamespaceKeyword */)); + break; + case 243 /* ExportAssignment */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -89525,6 +89808,29 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var decorator = ts.getAncestor(token, 147 /* Decorator */); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), + changes: changeTracker.getChanges() + }]; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -89680,7 +89986,7 @@ var ts; var className = classDeclaration.name.getText(); var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); + staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var initializeStaticAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), changes: staticInitializationChangeTracker.getChanges() @@ -89695,7 +90001,7 @@ var ts; } var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + propertyInitializationChangeTracker.insertNodeBefore(classDeclarationSourceFile, classConstructor.body.getLastToken(), propertyInitialization, { suffix: context.newLineCharacter }); var initializeAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), changes: propertyInitializationChangeTracker.getChanges() @@ -90276,9 +90582,6 @@ var ts; this.symbolIdToActionMap = []; } ImportCodeActionMap.prototype.addAction = function (symbolId, newAction) { - if (!newAction) { - return; - } var actions = this.symbolIdToActionMap[symbolId]; if (!actions) { this.symbolIdToActionMap[symbolId] = [newAction]; @@ -90297,7 +90600,7 @@ var ts; continue; } switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) { - case ModuleSpecifierComparison.Better: + case 0 /* Better */: // the new one is not worth considering if it is a new import. // However if it is instead a insertion into existing import, the user might want to use // the module specifier even it is worse by our standards. So keep it. @@ -90305,7 +90608,7 @@ var ts; return; } // falls through - case ModuleSpecifierComparison.Equal: + case 1 /* Equal */: // the current one is safe. But it is still possible that the new one is worse // than another existing one. For example, you may have new imports from "./foo/bar" // and "bar", when the new one is "bar/bar2" and the current one is "./foo/bar". The new @@ -90313,7 +90616,7 @@ var ts; // but the new one is worse than the other one, so should not add to the list. updatedNewImports.push(existingAction); break; - case ModuleSpecifierComparison.Worse: + case 2 /* Worse */: // the existing one is worse, remove from the list. continue; } @@ -90337,14 +90640,14 @@ var ts; }; ImportCodeActionMap.prototype.compareModuleSpecifiers = function (moduleSpecifier1, moduleSpecifier2) { if (moduleSpecifier1 === moduleSpecifier2) { - return ModuleSpecifierComparison.Equal; + return 1 /* Equal */; } // if moduleSpecifier1 (ms1) is a substring of ms2, then it is better if (moduleSpecifier2.indexOf(moduleSpecifier1) === 0) { - return ModuleSpecifierComparison.Better; + return 0 /* Better */; } if (moduleSpecifier1.indexOf(moduleSpecifier2) === 0) { - return ModuleSpecifierComparison.Worse; + return 2 /* Worse */; } // if both are relative paths, and ms1 has fewer levels, then it is better if (ts.isExternalModuleNameRelative(moduleSpecifier1) && ts.isExternalModuleNameRelative(moduleSpecifier2)) { @@ -90352,13 +90655,13 @@ var ts; var moduleSpecifier1LevelCount = (moduleSpecifier1.match(regex) || []).length; var moduleSpecifier2LevelCount = (moduleSpecifier2.match(regex) || []).length; return moduleSpecifier1LevelCount < moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Better + ? 0 /* Better */ : moduleSpecifier1LevelCount === moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Equal - : ModuleSpecifierComparison.Worse; + ? 1 /* Equal */ + : 2 /* Worse */; } // the equal cases include when the two specifiers are not comparable. - return ModuleSpecifierComparison.Equal; + return 1 /* Equal */; }; return ImportCodeActionMap; }()); @@ -91130,6 +91433,574 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + ], + getCodeActions: getActionsForAddExplicitTypeAnnotation + }); + function getActionsForAddExplicitTypeAnnotation(_a) { + var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var writer; + if (ts.isInJavaScriptFile(token)) { + return undefined; + } + switch (token.kind) { + case 71 /* Identifier */: + case 24 /* DotDotDotToken */: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + // Allowed + break; + default: + return undefined; + } + var containingFunction = ts.getContainingFunction(token); + var checker = program.getTypeChecker(); + switch (errorCode) { + // Variable and Property declarations + 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: + return getCodeActionForVariableDeclaration(token.parent); + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: + return getCodeActionForVariableUsage(token); + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessor(containingFunction)) { + return getCodeActionForSetAccessor(containingFunction); + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + return getCodeActionForParameters(token.parent); + // 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: + return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined; + } + return undefined; + function getCodeActionForVariableDeclaration(declaration) { + if (!ts.isIdentifier(declaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(declaration.name); + var typeString = type && typeToString(type, declaration); + if (!typeString) { + return undefined; + } + return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), ": " + typeString); + } + function getCodeActionForVariableUsage(token) { + var symbol = checker.getSymbolAtLocation(token); + return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration); + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 152 /* Constructor */: + return true; + case 186 /* FunctionExpression */: + return !!declaration.name; + } + return false; + } + function getCodeActionForParameters(parameterDeclaration) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return undefined; + } + var types = inferTypeForParametersFromUsage(containingFunction) || + ts.map(containingFunction.parameters, function (p) { return ts.isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name); }); + if (!types) { + return undefined; + } + var textChanges = ts.zipWith(containingFunction.parameters, types, function (parameter, type) { + if (type && !parameter.type && !parameter.initializer) { + var typeString = typeToString(type, containingFunction); + return typeString ? { + span: { start: parameter.end, length: 0 }, + newText: ": " + typeString + } : undefined; + } + }).filter(function (c) { return !!c; }); + return textChanges.length ? [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: textChanges + }] + }] : undefined; + } + function getCodeActionForSetAccessor(setAccessorDeclaration) { + var setAccessorParameter = setAccessorDeclaration.parameters[0]; + if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) || + inferTypeForVariableFromUsage(setAccessorParameter.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), ": " + typeString); + } + function getCodeActionForGetAccessor(getAccessorDeclaration) { + if (!ts.isIdentifier(getAccessorDeclaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + var closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, 20 /* CloseParenToken */); + return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), ": " + typeString); + } + function createCodeActions(name, start, typeString) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_type_of_0_from_usage), [name]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: start, length: 0 }, + newText: typeString + }] + }] + }]; + } + function getReferences(token) { + var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), token.getSourceFile(), token.getStart()); + ts.Debug.assert(!!references, "Found no references!"); + ts.Debug.assert(references.length === 1, "Found more references than expected"); + return ts.map(references[0].references, function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false); }); + } + function inferTypeForVariableFromUsage(token) { + return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken); + } + function inferTypeForParametersFromUsage(containingFunction) { + switch (containingFunction.kind) { + case 152 /* Constructor */: + case 186 /* FunctionExpression */: + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + var isConstructor = containingFunction.kind === 152 /* Constructor */; + var searchToken = isConstructor ? + getFirstChildOfKind(containingFunction, sourceFile, 123 /* ConstructorKeyword */) : + containingFunction.name; + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken); + } + } + } + function getTypeAccessiblityWriter() { + if (!writer) { + var str_1 = ""; + var typeIsAccessible_1 = true; + var writeText = function (text) { return str_1 += text; }; + writer = { + string: function () { return typeIsAccessible_1 ? str_1 : undefined; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + writeLine: function () { return str_1 += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { str_1 = ""; typeIsAccessible_1 = true; }, + trackSymbol: function (symbol, declaration, meaning) { + if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { + typeIsAccessible_1 = false; + } + }, + reportInaccessibleThisError: function () { typeIsAccessible_1 = false; }, + reportPrivateInBaseOfClassExpression: function () { typeIsAccessible_1 = false; }, + }; + } + writer.clear(); + return writer; + } + function typeToString(type, enclosingDeclaration) { + var writer = getTypeAccessiblityWriter(); + checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); + return writer.string(); + } + function getFirstChildOfKind(node, sourcefile, kind) { + for (var _i = 0, _a = node.getChildren(sourcefile); _i < _a.length; _i++) { + var child = _a[_i]; + if (child.kind === kind) + return child; + } + return undefined; + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypeFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return getTypeFromUsageContext(usageContext, checker); + } + InferFromReference.inferTypeFromReferences = inferTypeFromReferences; + function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { + if (declaration.parameters) { + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var isConstructor = declaration.kind === 152 /* Constructor */; + var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; + if (callContexts) { + var paramTypes = []; + for (var parameterIndex = 0; parameterIndex < declaration.parameters.length; parameterIndex++) { + var types = []; + var isRestParameter_1 = ts.isRestParameter(declaration.parameters[parameterIndex]); + for (var _a = 0, callContexts_1 = callContexts; _a < callContexts_1.length; _a++) { + var callContext = callContexts_1[_a]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter_1) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + paramTypes[parameterIndex] = isRestParameter_1 ? checker.createArrayType(type) : type; + } + } + return paramTypes; + } + } + return undefined; + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 193 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 192 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 194 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 257 /* CaseClause */: + case 258 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 181 /* CallExpression */: + case 182 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 179 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 180 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isPartOfExpression(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + usageContext.isNumber = true; + break; + case 37 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 40 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: + // ShiftOperator + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 48 /* AmpersandToken */: + case 49 /* BarToken */: + case 50 /* CaretToken */: + // CompoundAssignmentOperator + case 60 /* MinusEqualsToken */: + case 62 /* AsteriskAsteriskEqualsToken */: + case 61 /* AsteriskEqualsToken */: + case 63 /* SlashEqualsToken */: + case 64 /* PercentEqualsToken */: + case 68 /* AmpersandEqualsToken */: + case 69 /* BarEqualsToken */: + case 70 /* CaretEqualsToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 38 /* MinusToken */: + // RelationalOperator + case 27 /* LessThanToken */: + case 30 /* LessThanEqualsToken */: + case 29 /* GreaterThanToken */: + case 31 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 272 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 59 /* PlusEqualsToken */: + case 37 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 272 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 84 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 262178 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 58 /* EqualsToken */: + case 32 /* EqualsEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 92 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 54 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 226 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 53 /* AmpersandAmpersandToken */: + case 26 /* CommaToken */: + case 93 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 181 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 84 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function getTypeFromUsageContext(usageContext, checker) { + if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { + return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); + } + else if (usageContext.isNumber) { + return checker.getNumberType(); + } + else if (usageContext.isString) { + return checker.getStringType(); + } + else if (usageContext.candidateTypes) { + return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), /*subtypeReduction*/ true)); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); + var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + return checker.createPromiseType(types.length ? checker.getUnionType(types, /*subtypeReduction*/ true) : checker.getAnyType()); + } + 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) { + var members_4 = 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); + members_4.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.numberIndexContext) { + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); + } + return checker.createAnonymousType(/*symbol*/ undefined, members_4, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + return undefined; + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = getTypeFromUsageContext(callContext.returnType, checker); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 8192 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return usageContext && usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/// /// /// /// @@ -91144,6 +92015,7 @@ var ts; /// /// /// +/// /* @internal */ var ts; (function (ts) { @@ -91297,7 +92169,8 @@ var ts; switch (assignmentBinaryExpression.right.kind) { case 186 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); copyComments(assignmentBinaryExpression, method); return method; @@ -91314,7 +92187,8 @@ var ts; var expression = arrowFunctionBody; bodyBlock = ts.createBlock([ts.createReturn(expression)]); } - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); copyComments(assignmentBinaryExpression, method); return method; @@ -91359,7 +92233,8 @@ var ts; if (initializer.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; @@ -91369,11 +92244,15 @@ var ts; if (node.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } } })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); @@ -91506,7 +92385,7 @@ var ts; Messages.FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); Messages.CannotExtractIdentifier = createMessage("Select more than a single identifier."); Messages.CannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); - Messages.CannotCombineWritesAndReturns = createMessage("Cannot combine writes and returns"); + Messages.CannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); Messages.CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); Messages.CannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); @@ -91694,7 +92573,7 @@ var ts; permittedJumps = 0 /* None */; break; case 207 /* Block */: - if (node.parent && node.parent.kind === 224 /* TryStatement */ && node.finallyBlock === node) { + if (node.parent && node.parent.kind === 224 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } @@ -91791,7 +92670,10 @@ var ts; // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class var containingClass = ts.getContainingClass(current); if (containingClass) { - return [containingClass]; + var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration); + return containingFunction + ? [containingFunction, containingClass] + : [containingClass]; } } var start = current; @@ -91817,14 +92699,15 @@ var ts; return scopes; } function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope; + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); context.cancellationToken.throwIfCancellationRequested(); - return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); } function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope; + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); context.cancellationToken.throwIfCancellationRequested(); var expression = ts.isExpression(target) ? target @@ -91942,7 +92825,7 @@ var ts; })(SpecialScope || (SpecialScope = {})); function getUniqueName(baseName, fileText) { var nameText = baseName; - for (var i = 1; fileText.indexOf(nameText) !== -1; i++) { + for (var i = 1; ts.stringContains(fileText, nameText); i++) { nameText = baseName + "_" + i; } return nameText; @@ -91951,7 +92834,7 @@ var ts; * Result of 'extractRange' operation for a specific scope. * Stores either a list of changes that should be applied to extract a range or a list of errors */ - function extractFunctionInScope(node, scope, _a, range, context) { + function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted function @@ -91997,9 +92880,10 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType); + returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); } - var _b = transformFunctionBody(node, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + ts.suppressLeadingAndTrailingTrivia(body); var newFunction; if (ts.isClassLike(scope)) { // always create private method in TypeScript files @@ -92025,7 +92909,10 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); } else { - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { + prefix: ts.isLineBreak(file.text.charCodeAt(scope.getLastToken().pos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter, + suffix: context.newLineCharacter + }); } var newNodes = []; // replace range with function call @@ -92038,33 +92925,89 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { call = ts.createAwait(call); } - if (writes) { + if (exposedVariableDeclarations.length && !writes) { + // No need to mix declarations and writes. + // How could any variables be exposed if there's a return statement? + ts.Debug.assert(!returnValueProperty); + ts.Debug.assert(!(range.facts & RangeFacts.HasReturn)); + if (exposedVariableDeclarations.length === 1) { + // Declaring exactly one variable: let x = newFunction(); + var variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns + variableDeclaration.parent.flags))); + } + else { + // Declaring multiple variables / return properties: + // let {x, y} = newFunction(); + var bindingElements = []; + var typeElements = []; + var commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + var sawExplicitType = false; + for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { + var variableDeclaration = exposedVariableDeclarations_1[_i]; + bindingElements.push(ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, + /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); + // Being returned through an object literal will have widened the type. + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + typeElements.push(ts.createPropertySignature( + /*modifiers*/ undefined, + /*name*/ variableDeclaration.symbol.name, + /*questionToken*/ undefined, + /*type*/ variableType, + /*initializer*/ undefined)); + sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined; + if (typeLiteral) { + ts.setEmitFlags(typeLiteral, 1 /* SingleLine */); + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), + /*type*/ typeLiteral, + /*initializer*/ call)], commonNodeFlags))); + } + } + else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping. + for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) { + var variableDeclaration = exposedVariableDeclarations_2[_c]; + var flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */) { + flags = (flags & ~2 /* Const */) | 1 /* Let */; + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags))); + } + } if (returnValueProperty) { // has both writes and return, need to create variable declaration to hold return value; newNodes.push(ts.createVariableStatement( - /*modifiers*/ undefined, [ts.createVariableDeclaration(returnValueProperty, ts.createKeywordTypeNode(119 /* AnyKeyword */))])); + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */))); } - var assignments = getPropertyAssignmentsForWrites(writes); + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (returnValueProperty) { assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); } // propagate writes back if (assignments.length === 1) { - if (returnValueProperty) { - newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); - } - else { - newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58 /* EqualsToken */, call))); - if (range.facts & RangeFacts.HasReturn) { - newNodes.push(ts.createReturn()); - } + // We would only have introduced a return value property if there had been + // other assignments to make. + ts.Debug.assert(!returnValueProperty); + newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); } } else { // emit e.g. // { a, b, __return } = newFunction(a, b); // return __return; - newNodes.push(ts.createStatement(ts.createBinary(ts.createObjectLiteral(assignments), 58 /* EqualsToken */, call))); + newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call))); if (returnValueProperty) { newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); } @@ -92081,20 +93024,28 @@ var ts; newNodes.push(call); } } - if (isReadonlyArray(range.range)) { - changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes, { - nodeSeparator: context.newLineCharacter, - suffix: context.newLineCharacter // insert newline only when replacing statements - }); - } - else { - changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); - } + var replacementRange = isReadonlyArray(range.range) + ? { pos: ts.first(range.range).getStart(), end: ts.last(range.range).end } + : { pos: range.range.getStart(), end: range.range.end }; + changeTracker.replaceRangeWithNodes(context.file, replacementRange, newNodes, { nodeSeparator: context.newLineCharacter }); var edits = changeTracker.getChanges(); var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; var renameFilename = renameRange.getSourceFile().fileName; var renameLocation = getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === undefined) { + return undefined; + } + var clone = ts.getSynthesizedDeepClone(typeNode); + var withoutParens = clone; + while (ts.isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 139 /* UndefinedKeyword */; }) + ? clone + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(139 /* UndefinedKeyword */)]); + } } /** * Result of 'extractRange' operation for a specific scope. @@ -92109,8 +93060,9 @@ var ts; var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS ? undefined - : checker.typeToTypeNode(checker.getContextualType(node)); + : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); var initializer = transformConstantInitializer(node, substitutions); + ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); if (ts.isClassLike(scope)) { ts.Debug.assert(!isJS); // See CannotExtractToJSClass @@ -92131,7 +93083,7 @@ var ts; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, { suffix: context.newLineCharacter + context.newLineCharacter }); // Consume - changeTracker.replaceNodeWithNodes(context.file, node, [localReference], { nodeSeparator: context.newLineCharacter }); + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); } else { var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); @@ -92281,21 +93233,22 @@ var ts; return functionReference; } } - function transformFunctionBody(body, writes, substitutions, hasReturn) { - if (ts.isBlock(body) && !writes && substitutions.size === 0) { - // already block, no writes to propagate back, no substitutions - can use node as is + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) { + var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; + if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { + // already block, no declarations or writes to propagate back, no substitutions - can use node as is return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; } var returnValueProperty; var ignoreReturns = false; var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions - if (writes || substitutions.size) { + if (hasWritesOrVariableDeclarations || substitutions.size) { var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); - if (writes && !hasReturn && ts.isStatement(body)) { + if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) { // add return at the end to propagate writes back in case if control flow falls out of the function body // it is ok to know that range has at least one return since it we only allow unconditional returns - var assignments = getPropertyAssignmentsForWrites(writes); + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (assignments.length === 1) { rewrittenStatements.push(ts.createReturn(assignments[0].name)); } @@ -92309,8 +93262,8 @@ var ts; return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 219 /* ReturnStatement */ && writes) { - var assignments = getPropertyAssignmentsForWrites(writes); + if (!ignoreReturns && node.kind === 219 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { returnValueProperty = "__return"; @@ -92328,7 +93281,7 @@ var ts; var oldIgnoreReturns = ignoreReturns; ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node); var substitution = substitutions.get(ts.getNodeId(node).toString()); - var result = substitution ? substitution() : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); ignoreReturns = oldIgnoreReturns; return result; } @@ -92340,7 +93293,7 @@ var ts; : initializer; function visitor(node) { var substitution = substitutions.get(ts.getNodeId(node).toString()); - return substitution ? substitution() : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); } } function getStatementsOrClassElements(scope) { @@ -92375,8 +93328,8 @@ var ts; ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. var prevMember = undefined; var allProperties = true; - for (var _i = 0, members_4 = members; _i < members_4.length; _i++) { - var member = members_4[_i]; + for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { + var member = members_5[_i]; if (member.pos > maxPos) { return prevMember || members[0]; } @@ -92421,8 +93374,14 @@ var ts; } } } - function getPropertyAssignmentsForWrites(writes) { - return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); + var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + return variableAssignments === undefined + ? writeAssignments + : writeAssignments === undefined + ? variableAssignments + : variableAssignments.concat(writeAssignments); } function isReadonlyArray(v) { return ts.isArray(v); @@ -92455,6 +93414,9 @@ var ts; var functionErrorsPerScope = []; var constantErrorsPerScope = []; var visibleDeclarationsInExtractedRange = []; + var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID + var exposedVariableDeclarations = []; + var firstExposedNonVariableDeclaration = undefined; var expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) @@ -92493,7 +93455,6 @@ var ts; } var seenUsages = ts.createMap(); var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; - var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range; var inGenericContext = isInGenericContext(unmodifiedNode); collectUsages(target); @@ -92531,6 +93492,14 @@ var ts; // copy allTypeParameterUsages into all remaining scopes. ts.Debug.assert(i_1 === scopes.length); } + // If there are any declarations in the extracted block that are used in the same enclosing + // lexical scope, we can't move the extraction "up" as those declarations will become unreachable + if (visibleDeclarationsInExtractedRange.length) { + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) + ? scopes[0] + : ts.getEnclosingBlockScopeContainer(scopes[0]); + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } var _loop_8 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. @@ -92552,8 +93521,10 @@ var ts; } } }); - if (hasWrite && !isReadonlyArray(targetRange.range) && ts.isExpression(targetRange.range)) { - var diag = ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns); + // If an expression was extracted, then there shouldn't have been any variable declarations. + ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + var diag = ts.createDiagnosticForNode(targetRange.range, Messages.CannotWriteInExpression); functionErrorsPerScope[i].push(diag); constantErrorsPerScope[i].push(diag); } @@ -92562,16 +93533,16 @@ var ts; functionErrorsPerScope[i].push(diag); constantErrorsPerScope[i].push(diag); } + else if (firstExposedNonVariableDeclaration) { + var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.CannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } }; for (var i = 0; i < scopes.length; i++) { _loop_8(i); } - // If there are any declarations in the extracted block that are used in the same enclosing - // lexical scope, we can't move the extraction "up" as those declarations will become unreachable - if (visibleDeclarationsInExtractedRange.length) { - ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); - } - return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope }; + return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function hasTypeParameters(node) { return ts.isDeclarationWithTypeParameters(node) && node.typeParameters !== undefined && @@ -92605,7 +93576,7 @@ var ts; recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { - visibleDeclarationsInExtractedRange.push(node.symbol); + visibleDeclarationsInExtractedRange.push(node); } if (ts.isAssignmentExpression(node)) { // use 'write' as default usage for values @@ -92648,11 +93619,7 @@ var ts; } } function recordUsagebySymbol(identifier, usage, isTypeName) { - // If the identifier is both a property name and its value, we're only interested in its value - // (since the name is a declaration and will be included in the extracted range). - var symbol = identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier - ? checker.getShorthandAssignmentValueSymbol(identifier.parent) - : checker.getSymbolAtLocation(identifier); + var symbol = getSymbolReferencedByIdentifier(identifier); if (!symbol) { // cannot find symbol - do nothing return undefined; @@ -92736,37 +93703,52 @@ var ts; return; } // Otherwise check and recurse. - var sym = checker.getSymbolAtLocation(node); - if (sym && visibleDeclarationsInExtractedRange.some(function (d) { return d === sym; })) { - var diag = ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity); - for (var _i = 0, functionErrorsPerScope_2 = functionErrorsPerScope; _i < functionErrorsPerScope_2.length; _i++) { - var errors = functionErrorsPerScope_2[_i]; - errors.push(diag); + var sym = ts.isIdentifier(node) + ? getSymbolReferencedByIdentifier(node) + : checker.getSymbolAtLocation(node); + if (sym) { + var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; }); + if (decl) { + if (ts.isVariableDeclaration(decl)) { + var idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } + else { + // CONSIDER: this includes binding elements, which we could + // expose in the same way as variables. + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } } - for (var _a = 0, constantErrorsPerScope_2 = constantErrorsPerScope; _a < constantErrorsPerScope_2.length; _a++) { - var errors = constantErrorsPerScope_2[_a]; - errors.push(diag); - } - return true; - } - else { - ts.forEachChild(node, checkForUsedDeclarations); } + ts.forEachChild(node, checkForUsedDeclarations); + } + /** + * Return the symbol referenced by an identifier (even if it declares a different symbol). + */ + function getSymbolReferencedByIdentifier(identifier) { + // If the identifier is both a property name and its value, we're only interested in its value + // (since the name is a declaration and will be included in the extracted range). + return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); } function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { if (!symbol) { return undefined; } if (symbol.getDeclarations().some(function (d) { return d.parent === scopeDecl; })) { - return function () { return ts.createIdentifier(symbol.name); }; + return ts.createIdentifier(symbol.name); } var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode); if (prefix === undefined) { return undefined; } return isTypeNode - ? function () { return ts.createQualifiedName(prefix(), ts.createIdentifier(symbol.name)); } - : function () { return ts.createPropertyAccess(prefix(), symbol.name); }; + ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) + : ts.createPropertyAccess(prefix, symbol.name); } } function getParentNodeInSpan(node, file, span) { @@ -94402,7 +95384,7 @@ var ts; } function isNodeModulesFile(path) { var node_modulesFolderName = "/node_modules/"; - return path.indexOf(node_modulesFolderName) !== -1; + return ts.stringContains(path, node_modulesFolderName); } } function getRenameInfo(fileName, position) { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 666b483ad3e..89fe29530e1 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -1442,6 +1442,10 @@ declare namespace ts { interface JSDocUnknownTag extends JSDocTag { kind: SyntaxKind.JSDocTag; } + /** + * Note that `@extends` is a synonym of `@augments`. + * Both tags are represented by this interface. + */ interface JSDocAugmentsTag extends JSDocTag { kind: SyntaxKind.JSDocAugmentsTag; class: ExpressionWithTypeArguments & { @@ -1473,7 +1477,7 @@ declare namespace ts { interface JSDocPropertyLikeTag extends JSDocTag, Declaration { parent: JSDoc; name: EntityName; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ isNameFirst: boolean; isBracketed: boolean; @@ -1727,6 +1731,10 @@ declare namespace ts { signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + /** + * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead + * This will be removed in a future version. + */ getSymbolDisplayBuilder(): SymbolDisplayBuilder; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; @@ -2921,6 +2929,8 @@ declare namespace ts { function getJSDocReturnType(node: Node): TypeNode | undefined; /** Get all JSDoc tags related to a node, including those on parent nodes. */ function getJSDocTags(node: Node): ReadonlyArray | undefined; + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray | undefined; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -3113,6 +3123,8 @@ declare namespace ts { function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node: Node): boolean; + function isSetAccessor(node: Node): node is SetAccessorDeclaration; + function isGetAccessor(node: Node): node is GetAccessorDeclaration; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 3ea6fca626e..ca24c94ce30 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -1363,7 +1363,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.6"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -1542,10 +1542,12 @@ var ts; } ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { + var result = []; Debug.assert(arrayA.length === arrayB.length); for (var i = 0; i < arrayA.length; i++) { - callback(arrayA[i], arrayB[i], i); + result.push(callback(arrayA[i], arrayB[i], i)); } + return result; } ts.zipWith = zipWith; function zipToMap(keys, values) { @@ -1674,22 +1676,6 @@ var ts; return array; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var item = array_2[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var i = 0; i < array.length; i++) { @@ -1745,8 +1731,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1927,8 +1913,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (predicate(v)) { return true; } @@ -1954,8 +1940,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + loop: for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -2048,8 +2034,8 @@ var ts; ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; // Note: we need the following type assertion because of GH #17069 result += v[prop]; } @@ -2422,8 +2408,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; @@ -2864,7 +2850,7 @@ var ts; } ts.getDirectoryPath = getDirectoryPath; function isUrl(path) { - return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + return path && !isRootedDiskPath(path) && stringContains(path, "://"); } ts.isUrl = isUrl; function pathIsRelative(path) { @@ -3120,8 +3106,12 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; function hasExtension(fileName) { - return getBaseFileName(fileName).indexOf(".") >= 0; + return stringContains(getBaseFileName(fileName), "."); } ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { @@ -4686,6 +4676,7 @@ var ts; Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), 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."), @@ -5013,6 +5004,7 @@ var ts; A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), 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}'."), @@ -5336,9 +5328,10 @@ var ts; Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), - JSDoc_augments_is_not_attached_to_a_class_declaration: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_augments_is_not_attached_to_a_class_declaration_8022", "JSDoc '@augments' is not attached to a class declaration."), - JSDoc_augments_0_does_not_match_the_extends_1_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023", "JSDoc '@augments {0}' does not match the 'extends {1}' clause."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), 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."), @@ -5370,7 +5363,7 @@ 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(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), - Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'."), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), @@ -5384,6 +5377,7 @@ var ts; Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'."), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), @@ -5392,6 +5386,8 @@ var ts; Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Infer_type_of_0_from_usage: diag(95009, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95009", "Infer type of '{0}' from usage."), + Infer_parameter_types_from_usage: diag(95010, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95010", "Infer parameter types from usage."), }; })(ts || (ts = {})); /// @@ -8707,27 +8703,14 @@ var ts; } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { - return isRestParameter(ts.lastOrUndefined(s.parameters)); + var last = ts.lastOrUndefined(s.parameters); + return last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; - function hasDeclaredRestParameter(s) { - return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); - } - ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 274 /* JSDocVariadicType */ || - ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274 /* JSDocVariadicType */; })) { - return true; - } - } - return isDeclaredRestParam(node); + return node.dotDotDotToken !== undefined; } ts.isRestParameter = isRestParameter; - function isDeclaredRestParam(node) { - return node && node.dotDotDotToken !== undefined; - } - ts.isDeclaredRestParam = isDeclaredRestParam; var AssignmentKind; (function (AssignmentKind) { AssignmentKind[AssignmentKind["None"] = 0] = "None"; @@ -11010,27 +10993,35 @@ var ts; if (!declaration) { return undefined; } - if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143 /* QualifiedName */) { - return declaration.name.right; - } - if (declaration.kind === 194 /* BinaryExpression */) { - var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { - case 1 /* ExportsProperty */: - case 4 /* ThisProperty */: - case 5 /* Property */: - case 3 /* PrototypeProperty */: - return expr.left.name; - default: - return undefined; + switch (declaration.kind) { + case 284 /* JSDocPropertyTag */: + case 279 /* JSDocParameterTag */: { + var name = declaration.name; + if (name.kind === 143 /* QualifiedName */) { + return name.right; + } + break; + } + case 194 /* BinaryExpression */: { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + default: + return undefined; + } + } + case 283 /* JSDocTypedefTag */: + return getNameOfJSDocTypedef(declaration); + case 243 /* ExportAssignment */: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; } } - else if (declaration.kind === 283 /* JSDocTypedefTag */) { - return getNameOfJSDocTypedef(declaration); - } - else { - return declaration.name; - } + return declaration.name; } ts.getNameOfDeclaration = getNameOfDeclaration; /** @@ -11143,6 +11134,12 @@ var ts; var tags = getJSDocTags(node); return ts.find(tags, function (doc) { return doc.kind === kind; }); } + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node, kind) { + var tags = getJSDocTags(node); + return ts.filter(tags, function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -12493,6 +12490,14 @@ var ts; return node.kind >= 276 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 154 /* SetAccessor */; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 153 /* GetAccessor */; + } + ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ /* @internal */ function hasJSDocNodes(node) { @@ -18161,6 +18166,7 @@ var ts; if (tagName) { switch (tagName.escapedText) { case "augments": + case "extends": tag = parseAugmentsTag(atToken, tagName); break; case "class": @@ -18456,7 +18462,7 @@ var ts; if (typeExpression && typeExpression.type.kind === 164 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); } @@ -18732,8 +18738,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var node = array_7[_i]; visitNode(node); } } @@ -18870,8 +18876,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } return; @@ -19219,6 +19225,14 @@ var ts; // state used to aggregate transform flags during bind. var subtreeTransformFlags = 0 /* None */; var skipTransformFlagAggregation; + /** + * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) + * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) + * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. + */ + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } function bindSourceFile(f, opts) { file = f; options = opts; @@ -19293,6 +19307,9 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { + if (node.kind === 243 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } var name = ts.getNameOfDeclaration(node); if (name) { if (ts.isAmbientModule(node)) { @@ -19323,8 +19340,6 @@ var ts; return "__index" /* Index */; case 244 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 243 /* ExportAssignment */: - return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; case 194 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { // module.exports = ... @@ -19440,9 +19455,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } @@ -20175,7 +20190,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } if (!node.statement || node.statement.kind !== 212 /* DoStatement */) { // do statement sets current flow inside bindDoStatement @@ -20669,7 +20684,7 @@ var ts; !ts.isInAmbientContext(node)) { // Report error only if there are no parse errors in file if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); } } } @@ -20764,7 +20779,7 @@ var ts; } function checkStrictModeNumericLiteral(node) { if (inStrictMode && node.numericLiteralFlags & 4 /* Octal */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } function checkStrictModePostfixUnaryExpression(node) { @@ -21057,7 +21072,7 @@ var ts; // falls through case 284 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 272 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); @@ -21114,20 +21129,20 @@ var ts; } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } if (node.parent.kind !== 265 /* SourceFile */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { var parent_1 = node.parent; if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } } @@ -21166,15 +21181,12 @@ var ts; function isExportsOrModuleExportsOrAlias(node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); } function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (ts.isIdentifier(node)) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - return false; + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(node) { return isExportsOrModuleExportsOrAlias(node) || @@ -21238,17 +21250,19 @@ var ts; // follow the function declaration var leftSideOfAssignment = node.left; var target = leftSideOfAssignment.expression; - // Fix up parent pointers since we're going to use these nodes before we bind into them - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - // This can be an alias for the 'exports' or 'module.exports' names, e.g. - // var util = module.exports; - // util.property = function ... - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); + if (ts.isIdentifier(target)) { + // Fix up parent pointers since we're going to use these nodes before we bind into them + leftSideOfAssignment.parent = node; + target.parent = leftSideOfAssignment; + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); + } } } function lookupSymbolForName(name) { @@ -21304,7 +21318,7 @@ var ts; if (node.name) { node.name.parent = node; } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); } symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); prototypeSymbol.parent = symbol; @@ -21520,6 +21534,11 @@ var ts; } if (expression.kind === 91 /* ImportKeyword */) { transformFlags |= 67108864 /* 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 */; + } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; @@ -23316,7 +23335,7 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : withoutAtTypePrefix; } @@ -23610,6 +23629,23 @@ var ts; return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getBooleanType: function () { return booleanType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, isArrayLikeType: isArrayLikeType, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, @@ -23657,6 +23693,7 @@ var ts; anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var markerSuperType = createType(16384 /* TypeParameter */); var markerSubType = createType(16384 /* TypeParameter */); markerSubType.constraint = markerSuperType; @@ -23858,6 +23895,12 @@ var ts; CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; })(CheckMode || (CheckMode = {})); + var CallbackCheck; + (function (CallbackCheck) { + CallbackCheck[CallbackCheck["None"] = 0] = "None"; + CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; + CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; + })(CallbackCheck || (CallbackCheck = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); @@ -24226,6 +24269,7 @@ var ts; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; + var lastNonBlockLocation; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; @@ -24437,13 +24481,16 @@ var ts; } break; } + if (location.kind !== 207 /* Block */) { + lastNonBlockLocation = location; + } lastLocation = location; location = location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; } if (!result) { @@ -27162,13 +27209,13 @@ var ts; if (parentType === unknownType) { return unknownType; } - // If no type was specified or inferred for parent, or if the specified or inferred type is any, - // infer from the initializer of the binding element if one is present. Otherwise, go with the - // undefined or any type of the parent. - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } + // If no type was specified or inferred for parent, + // infer from the initializer of the binding element if one is present. + // Otherwise, go with the undefined type of the parent. + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { return parentType; } var type; @@ -27194,9 +27241,6 @@ var ts; // computed properties with non-literal names are treated as 'any' return anyType; } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } // 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. var text = ts.getTextOfPropertyName(name); @@ -28944,27 +28988,48 @@ var ts; function getApparentTypeOfIntersectionType(type) { return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); } + function getResolvedTypeParameterDefault(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + // To block recursion, set the initial value to the resolvingDefaultType. + typeParameter.default = resolvingDefaultType; + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + // If we have not been called recursively, set the correct default type. + typeParameter.default = defaultType; + } + } + } + else if (typeParameter.default === resolvingDefaultType) { + // If we are called recursively for this type parameter, mark the default as circular. + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } /** * Gets the default type for a type parameter. * * If the type parameter is the result of an instantiation, this gets the instantiated - * default type of its target. If the type parameter has no default type, `undefined` - * is returned. - * - * This function *does not* perform a circularity check. + * default type of its target. If the type parameter has no default type or the default is + * circular, `undefined` is returned. */ function getDefaultFromTypeParameter(typeParameter) { - if (!typeParameter.default) { - if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); - typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; - } - else { - var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; - } - } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + /** + * Indicates whether the declaration of a typeParameter has a default type. + */ + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, @@ -29128,7 +29193,7 @@ var ts; return getIndexTypeOfStructuredType(getApparentType(type), kind); } function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { + if (isObjectTypeWithInferableIndex(type)) { var propTypes = []; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; @@ -29232,7 +29297,7 @@ var ts; var minTypeArgumentCount = 0; if (typeParameters) { for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { + if (!hasTypeParameterDefault(typeParameters[i])) { minTypeArgumentCount = i + 1; } } @@ -30572,7 +30637,7 @@ var ts; * this function should be called in a left folding style, with left = previous result of getSpreadType * and right = the new element to be spread. */ - function getSpreadType(left, right) { + function getSpreadType(left, right, symbol, propagatedFlags) { if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { return anyType; } @@ -30583,10 +30648,10 @@ var ts; return left; } if (left.flags & 65536 /* Union */) { - return mapType(left, function (t) { return getSpreadType(t, right); }); + return mapType(left, function (t) { return getSpreadType(t, right, symbol, propagatedFlags); }); } if (right.flags & 65536 /* Union */) { - return mapType(right, function (t) { return getSpreadType(left, t); }); + return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } if (right.flags & 16777216 /* NonPrimitive */) { return nonPrimitiveType; @@ -30643,7 +30708,12 @@ var ts; members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); } } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var spread = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + spread.flags |= propagatedFlags; + spread.flags |= 1048576 /* FreshLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */; + spread.symbol = symbol; + return spread; } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { @@ -30945,11 +31015,11 @@ var ts; // The first time an anonymous type is instantiated we compute and store a list of the type // parameters that are in scope (and therefore potentially referenced). For type literals that // aren't the right hand side of a generic type alias declaration we optimize by reducing the - // set of type parameters to those that are actually referenced somewhere in the literal. + // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true) || ts.emptyArray; typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? - ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : outerTypeParameters; links.typeParameters = typeParameters; if (typeParameters.length) { @@ -30974,13 +31044,27 @@ var ts; } return type; } - function isTypeParameterReferencedWithin(tp, node) { - return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); - function checkThis(node) { - return node.kind === 169 /* ThisType */ || ts.forEachChild(node, checkThis); + function isTypeParameterPossiblyReferenced(tp, node) { + // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks + // between the node and the type parameter declaration, if the node contains actual references to the + // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_1 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 207 /* Block */ ? "quit" : n === container_1; })) { + return ts.forEachChild(node, containsReference); + } } - function checkIdentifier(node) { - return node.kind === 71 /* Identifier */ && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + return true; + function containsReference(node) { + switch (node.kind) { + case 169 /* ThisType */: + return tp.isThisType; + case 71 /* Identifier */: + return !tp.isThisType && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp; + case 162 /* TypeQuery */: + return true; + } + return ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -31181,13 +31265,13 @@ var ts; return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, /*checkAsCallback*/ false, ignoreReturnTypes, /*reportErrors*/ false, + return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; } /** * See signatureRelatedTo, compareSignaturesIdentical */ - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; @@ -31200,7 +31284,7 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = strictFunctionTypes && kind !== 151 /* MethodDeclaration */ && + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 151 /* MethodDeclaration */ && kind !== 150 /* MethodSignature */ && kind !== 152 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); @@ -31227,21 +31311,21 @@ var ts; for (var i = 0; i < checkCount; i++) { var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); // 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 - // function types with a single call signature, we known we are relating two callback parameters. In + // function types with a single call signature, we know we are relating two callback parameters. In // that case it is sufficient to only relate the parameters of the signatures co-variantly because, // similar to return values, callback parameters are output positions. This means that a Promise, // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) // with respect to T. + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && (getFalsyFlags(sourceType) & 6144 /* Nullable */) === (getFalsyFlags(targetType) & 6144 /* Nullable */); var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, /*checkAsCallback*/ true, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.symbolName(sourceParams[i < sourceMax ? i : sourceMax]), ts.symbolName(targetParams[i < targetMax ? i : targetMax])); @@ -31272,7 +31356,7 @@ var ts; // When relating callback signatures, we still need to relate return types bi-variantly as otherwise // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } // wouldn't be co-variant for T without this rule. - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || + result &= callbackCheck === 1 /* Bivariant */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || compareTypes(sourceReturnType, targetReturnType, reportErrors); } } @@ -31682,6 +31766,13 @@ var ts; (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } + if (target.flags & 65536 /* Union */) { + var discriminantType = findMatchingDiscriminantType(source, target); + if (discriminantType) { + // check excess properties against discriminant type only, not the entire union + return hasExcessProperties(source, discriminantType, reportErrors); + } + } var _loop_4 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -31758,22 +31849,25 @@ var ts; return 0 /* False */; } function findMatchingDiscriminantType(source, target) { + var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.escapedName)) { - 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)) { - return type; + var sourceProperty = findSingleDiscriminantProperty(sourceProperties, target); + if (sourceProperty) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var type = _a[_i]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); + if (targetType && isRelatedTo(sourceType, targetType)) { + if (match) { + return undefined; } + match = type; } } } } + return match; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -32231,8 +32325,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); if (!targetProp) { return 0 /* False */; @@ -32320,8 +32414,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, - /*checkAsCallback*/ false, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -32382,7 +32475,7 @@ var ts; // if T is related to U. return kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); } - if (isObjectLiteralType(source)) { + if (isObjectTypeWithInferableIndex(source)) { var related = -1 /* True */; if (kind === 0 /* String */) { var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); @@ -32852,11 +32945,11 @@ var ts; return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; } /** - * Return true if type was inferred from an object literal or written as an object type literal + * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module * with no call or construct signatures. */ - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */)) !== 0 && + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 512 /* ValueModule */)) !== 0 && getSignaturesOfType(type, 0 /* Call */).length === 0 && getSignaturesOfType(type, 1 /* Construct */).length === 0; } @@ -33663,6 +33756,19 @@ var ts; } return false; } + function findSingleDiscriminantProperty(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + return undefined; + } + result = sourceProperty; + } + } + return result; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -36144,7 +36250,7 @@ var ts; checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -36156,7 +36262,7 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return unknownType; } - spread = getSpreadType(spread, type); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags); offset = i + 1; continue; } @@ -36198,14 +36304,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768 /* Object */) { - // only set the symbol and flags if this is a (fresh) object type - spread.flags |= propagatedFlags; - spread.flags |= 1048576 /* FreshLiteral */; - spread.objectFlags |= 128 /* ObjectLiteral */; - spread.symbol = node.symbol; + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); } return spread; } @@ -36256,7 +36355,7 @@ var ts; */ function isUnhyphenatedJsxName(name) { // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers - return name.indexOf("-") < 0; + return !ts.stringContains(name, "-"); } /** * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name @@ -36315,7 +36414,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); attributesArray = []; attributesTable = ts.createSymbolTable(); } @@ -36324,7 +36423,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*propagatedFlags*/ 0); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -36334,7 +36433,7 @@ var ts; if (!hasSpreadAnyType) { if (spread !== emptyObjectType) { if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); } attributesArray = getPropertiesOfType(spread); } @@ -37707,29 +37806,27 @@ var ts; } return getInferredTypes(context); } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJavaScriptFile(signature.declaration); var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable /* so far */) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } + 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 && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + 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; } } - return typeArgumentsAreAssignable; + return typeArgumentTypes; } /** * Check if the given signature can possibly be a signature called by the JSX opening-like element. @@ -38207,8 +38304,7 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } else if (candidateForTypeArgumentError) { - var typeArguments_1 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -38258,14 +38354,14 @@ var ts; var candidate = candidates[bestIndex]; var typeParameters = candidate.typeParameters; if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_2 = node.typeArguments.map(getTypeOfNode); - while (typeArguments_2.length > typeParameters.length) { - typeArguments_2.pop(); + var typeArguments_1 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_1.length > typeParameters.length) { + typeArguments_1.pop(); } - while (typeArguments_2.length < typeParameters.length) { - typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + while (typeArguments_1.length < typeParameters.length) { + typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); } - var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + var instantiated = createSignatureInstantiation(candidate, typeArguments_1); candidates[bestIndex] = instantiated; return instantiated; } @@ -38300,10 +38396,12 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); - if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false)) { + var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (typeArgumentResult) { + typeArgumentTypes = typeArgumentResult; + } + else { candidateForTypeArgumentError = originalCandidate; break; } @@ -38311,6 +38409,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { @@ -38579,6 +38678,11 @@ var ts; if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; @@ -38589,6 +38693,18 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); } + /** + * Sometimes, we have a decorator that could accept zero arguments, + * but is receiving too many arguments as part of the decorator invocation. + * In those cases, a user may have meant to *call* the expression before using it as a decorator. + */ + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, 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 @@ -40272,6 +40388,9 @@ var ts; if (!hasNonCircularBaseConstraint(typeParameter)) { error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } var constraintType = getConstraintOfTypeParameter(typeParameter); var defaultType = getDefaultFromTypeParameter(typeParameter); if (constraintType && defaultType) { @@ -40291,7 +40410,6 @@ var ts; checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - func = ts.getContainingFunction(node); if (!(func.kind === 152 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } @@ -41648,17 +41766,22 @@ var ts; } } function checkJSDocAugmentsTag(node) { - var cls = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(cls) && !ts.isClassExpression(cls)) { - error(cls, ts.Diagnostics.JSDoc_augments_is_not_attached_to_a_class_declaration); + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } + var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 277 /* JSDocAugmentsTag */); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } var name = getIdentifierFromEntityNameExpression(node.class.expression); - var extend = ts.getClassExtendsHeritageClauseElement(cls); + var extend = ts.getClassExtendsHeritageClauseElement(classLike); if (extend) { var className = getIdentifierFromEntityNameExpression(extend.expression); if (className && name.escapedText !== className.escapedText) { - error(name, ts.Diagnostics.JSDoc_augments_0_does_not_match_the_extends_1_clause, ts.idText(name), ts.idText(className)); + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); } } } @@ -41908,7 +42031,7 @@ var ts; } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -46671,6 +46794,9 @@ var ts; // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). + if (node === undefined) { + return undefined; + } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; setOriginalNode(clone, node); @@ -48937,6 +49063,16 @@ var ts; return node; } ts.setEmitFlags = setEmitFlags; + /** + * Sets flags that control emit behavior of a node. + */ + /* @internal */ + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; /** * Gets a custom text range to use when emitting source maps. */ @@ -51733,6 +51869,19 @@ var ts; } return values; } + /** + * Used in the module transformer to check if an expression is reasonably without sideeffect, + * and thus better to copy into multiple places rather than to cache in a temporary variable + * - this is mostly subjective beyond the requirement that the expression not be sideeffecting + */ + function isSimpleCopiableExpression(expression) { + return expression.kind === 9 /* StringLiteral */ || + expression.kind === 8 /* NumericLiteral */ || + expression.kind === 13 /* NoSubstitutionTemplateLiteral */ || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; })(ts || (ts = {})); /// /// @@ -52204,7 +52353,7 @@ var ts; ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; - ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; + ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; @@ -52215,6 +52364,7 @@ var ts; var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = typeof compilerOptions.strictNullChecks === "undefined" ? compilerOptions.strict : compilerOptions.strictNullChecks; var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); // Save the previous transformation hooks. @@ -52646,8 +52796,9 @@ var ts; var facts = 0 /* None */; if (ts.some(staticProperties)) facts |= 1 /* HasStaticInitializedProperties */; - if (ts.getClassExtendsHeritageClauseElement(node)) - facts |= 64 /* HasExtendsClause */; + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) + facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) facts |= 2 /* HasConstructorDecorators */; if (ts.childIsDecorated(node)) @@ -52771,7 +52922,7 @@ var ts; : undefined; var classDeclaration = ts.createClassDeclaration( /*decorators*/ undefined, modifiers, name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0)); // To better align with the old emitter, we should not emit a trailing source map // entry if the class has static properties. var emitFlags = ts.getEmitFlags(node); @@ -52880,7 +53031,7 @@ var ts; // ${members} // } var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0); + var members = transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0); var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, location); @@ -52936,11 +53087,11 @@ var ts; * Transforms the members of a class. * * @param node The current class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformClassMembers(node, hasExtendsClause) { + function transformClassMembers(node, isDerivedClass) { var members = []; - var constructor = transformConstructor(node, hasExtendsClause); + var constructor = transformConstructor(node, isDerivedClass); if (constructor) { members.push(constructor); } @@ -52951,9 +53102,9 @@ var ts; * Transforms (or creates) a constructor for a class. * * @param node The current class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformConstructor(node, hasExtendsClause) { + function transformConstructor(node, isDerivedClass) { // 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 @@ -52966,7 +53117,7 @@ var ts; return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause); + var body = transformConstructorBody(node, constructor, isDerivedClass); // constructor(${parameters}) { // ${body} // } @@ -52979,7 +53130,6 @@ var ts; * parameter property assignments or instance property initializers. * * @param constructor The constructor declaration. - * @param hasExtendsClause A value indicating whether the class has an extends clause. */ function transformConstructorParameters(constructor) { // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: @@ -53006,9 +53156,9 @@ var ts; * * @param node The current class. * @param constructor The current class constructor. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformConstructorBody(node, constructor, hasExtendsClause) { + function transformConstructorBody(node, constructor, isDerivedClass) { var statements = []; var indexOfFirstStatement = 0; resumeLexicalEnvironment(); @@ -53029,7 +53179,7 @@ var ts; var propertyAssignments = getParametersWithPropertyAssignments(constructor); ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); } - else if (hasExtendsClause) { + else if (isDerivedClass) { // Add a synthetic `super` call: // // super(...arguments); @@ -53759,6 +53909,15 @@ var ts; var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 168 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 130 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 139 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } var serializedIndividual = serializeTypeNode(typeNode); if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { // One of the individual is global object, return immediately @@ -53778,7 +53937,7 @@ var ts; } } // If we were able to find common type, use it - return serializedUnion; + return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never } /** * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with @@ -60580,7 +60739,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { - if (ts.forEach(node.arguments, containsYield)) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { // [source] // a.b(1, yield, 2); // @@ -62333,7 +62492,7 @@ var ts; default: return transformCommonJSModule; } } - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -62688,17 +62847,19 @@ var ts; } } function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: - return transformImportCallExpressionAMD(node); + return createImportCallExpressionAMD(argument, containsLexicalThis); case ts.ModuleKind.UMD: - return transformImportCallExpressionUMD(node); + return createImportCallExpressionUMD(argument, containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return transformImportCallExpressionCommonJS(node); + return createImportCallExpressionCommonJS(argument, containsLexicalThis); } } - function transformImportCallExpressionUMD(node) { + function createImportCallExpressionUMD(arg, containsLexicalThis) { // (function (factory) { // ... (regular UMD) // } @@ -62713,12 +62874,22 @@ var ts; // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ // }); needUMDDynamicImportHelper = true; - return ts.createConditional( - /*condition*/ ts.createIdentifier("__syncRequire"), - /*whenTrue*/ transformImportCallExpressionCommonJS(node), - /*whenFalse*/ transformImportCallExpressionAMD(node)); + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */); + return ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); + } } - function transformImportCallExpressionAMD(node) { + function createImportCallExpressionAMD(arg, containsLexicalThis) { // improt("./blah") // emit as // define(["require", "exports", "blah"], function (require, exports) { @@ -62727,30 +62898,71 @@ var ts; // }); var resolve = ts.createUniqueName("resolve"); var reject = ts.createUniqueName("reject"); - return ts.createNew(ts.createIdentifier("Promise"), - /*typeArguments*/ undefined, [ts.createFunctionExpression( + var parameters = [ + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + ]; + var body = ts.createBlock([ + ts.createStatement(ts.createCall(ts.createIdentifier("require"), + /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, body); + } + else { + func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), - ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)], - /*type*/ undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), - /*typeArguments*/ undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); } - function transformImportCallExpressionCommonJS(node) { + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { // import("./blah") // emit as // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ // We have to wrap require in then callback so that require is done in asynchronously // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately - return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []), "then"), - /*typeArguments*/ undefined, [ts.createFunctionExpression( + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); + var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, requireCall); + } + else { + func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, - /*parameters*/ undefined, - /*type*/ undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, node.arguments))]))]); + /*parameters*/ [], + /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)])); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); } /** * Visits an ImportDeclaration node. @@ -62906,10 +63118,10 @@ var ts; if (original && hasAssociatedEndOfDeclarationMarker(original)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); } return ts.singleOrMany(statements); } @@ -64649,7 +64861,7 @@ var ts; // }; // }); return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), - /*typeArguments*/ undefined, node.arguments); + /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); } /** * Visits a DestructuringAssignment to flatten destructuring to exported symbols. @@ -66222,7 +66434,7 @@ var ts; }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); - return comment.indexOf("@internal") >= 0; + return ts.stringContains(comment, "@internal"); } function stripInternal(node) { if (node) { @@ -68866,7 +69078,7 @@ var ts; // check if numeric literal is a decimal literal that was originally written with a dot var text = getLiteralTextOfNode(expression); return !expression.numericLiteralFlags - && text.indexOf(ts.tokenToString(23 /* DotToken */)) < 0; + && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -70610,8 +70822,7 @@ var ts; existingInfo.version = sourceFile.version; emitHandler.onUpdateSourceFile(program, sourceFile); } - else if (program.hasInvalidatedResolution(sourceFile.path) && - emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { + else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { registerChangedFile(sourceFile.path, sourceFile.fileName); } } @@ -71496,8 +71707,7 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, - hasInvalidatedResolution: hasInvalidatedResolution + redirectTargetsSet: redirectTargetsSet }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -71869,10 +72079,17 @@ var ts; if (file.hasNoDefaultLib) { return true; } - if (defaultLibraryPath && defaultLibraryPath.length !== 0) { - return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, /*ignoreCase*/ !host.useCaseSensitiveFileNames()); + if (!options.noLib) { + return false; + } + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + if (!options.lib) { + return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + else { + return ts.forEach(options.lib, function (libFileName) { return ts.compareStrings(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; }); } - return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); @@ -76511,6 +76728,64 @@ var ts; return position; } ts.getSourceFileImportLocation = getSourceFileImportLocation; + /** + * Creates a deep, memberwise clone of a node with no source map location. + * + * WARNING: This is an expensive operation and is only intended to be used in refactorings + * and code fixes (because those are triggered by explicit user actions). + */ + function getSynthesizedDeepClone(node) { + if (node === undefined) { + return undefined; + } + var visited = 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; + } + else if (ts.isNumericLiteral(clone_7)) { + clone_7.numericLiteralFlags = node.numericLiteralFlags; + } + clone_7.pos = node.pos; + clone_7.end = node.end; + return clone_7; + } + // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update + // the new node created by visitEachChild with the extra changes getSynthesizedClone + // would have made. + visited.parent = undefined; + return visited; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + /** + * Sets EmitFlags to suppress leading and trailing trivia on the node. + */ + /* @internal */ + function suppressLeadingAndTrailingTrivia(node) { + ts.Debug.assert(node !== undefined); + suppressLeading(node); + suppressTrailing(node); + function suppressLeading(node) { + ts.addEmitFlags(node, 512 /* NoLeadingComments */); + var firstChild = ts.forEachChild(node, function (child) { return child; }); + firstChild && suppressLeading(firstChild); + } + function suppressTrailing(node) { + ts.addEmitFlags(node, 1024 /* NoTrailingComments */); + var lastChild = undefined; + ts.forEachChild(node, function (child) { return (lastChild = child, undefined); }, function (children) { + // As an optimization, jump straight to the end of the list. + if (children.length) { + lastChild = ts.last(children); + } + return undefined; + }); + lastChild && suppressTrailing(lastChild); + } + } + ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; })(ts || (ts = {})); var ts; (function (ts) { @@ -77574,7 +77849,7 @@ var ts; var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = fragment.indexOf(ts.directorySeparator) !== -1; + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); @@ -77606,7 +77881,7 @@ var ts; } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module - var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; + var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; // Get modules that the type checker picked up var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); @@ -78909,6 +79184,11 @@ var ts; if (ts.isClassLike(location)) { return location; } + // class c { method() { } b| } + if (isFromClassElementDeclaration(location) && + location.parent.name === location) { + return location.parent.parent; + } break; default: if (isFromClassElementDeclaration(contextToken) && @@ -80581,9 +80861,6 @@ var ts; return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { - if (ts.isExportAssignment(decl)) { - return ts.isIdentifier(decl.expression) ? decl.expression.escapedText : undefined; - } var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 /* Identifier */ && name.escapedText; }); @@ -81022,7 +81299,7 @@ var ts; State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(this.checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { @@ -85639,13 +85916,19 @@ var ts; } if (symbolFlags & 2097152 /* Alias */) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 236 /* NamespaceExportDeclaration */) { - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129 /* NamespaceKeyword */)); - } - else { - displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); + switch (symbol.declarations[0].kind) { + case 236 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(129 /* NamespaceKeyword */)); + break; + case 243 /* ExportAssignment */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -89525,6 +89808,29 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var decorator = ts.getAncestor(token, 147 /* Decorator */); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), + changes: changeTracker.getChanges() + }]; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -89680,7 +89986,7 @@ var ts; var className = classDeclaration.name.getText(); var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); + staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var initializeStaticAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), changes: staticInitializationChangeTracker.getChanges() @@ -89695,7 +90001,7 @@ var ts; } var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + propertyInitializationChangeTracker.insertNodeBefore(classDeclarationSourceFile, classConstructor.body.getLastToken(), propertyInitialization, { suffix: context.newLineCharacter }); var initializeAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), changes: propertyInitializationChangeTracker.getChanges() @@ -90276,9 +90582,6 @@ var ts; this.symbolIdToActionMap = []; } ImportCodeActionMap.prototype.addAction = function (symbolId, newAction) { - if (!newAction) { - return; - } var actions = this.symbolIdToActionMap[symbolId]; if (!actions) { this.symbolIdToActionMap[symbolId] = [newAction]; @@ -90297,7 +90600,7 @@ var ts; continue; } switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) { - case ModuleSpecifierComparison.Better: + case 0 /* Better */: // the new one is not worth considering if it is a new import. // However if it is instead a insertion into existing import, the user might want to use // the module specifier even it is worse by our standards. So keep it. @@ -90305,7 +90608,7 @@ var ts; return; } // falls through - case ModuleSpecifierComparison.Equal: + case 1 /* Equal */: // the current one is safe. But it is still possible that the new one is worse // than another existing one. For example, you may have new imports from "./foo/bar" // and "bar", when the new one is "bar/bar2" and the current one is "./foo/bar". The new @@ -90313,7 +90616,7 @@ var ts; // but the new one is worse than the other one, so should not add to the list. updatedNewImports.push(existingAction); break; - case ModuleSpecifierComparison.Worse: + case 2 /* Worse */: // the existing one is worse, remove from the list. continue; } @@ -90337,14 +90640,14 @@ var ts; }; ImportCodeActionMap.prototype.compareModuleSpecifiers = function (moduleSpecifier1, moduleSpecifier2) { if (moduleSpecifier1 === moduleSpecifier2) { - return ModuleSpecifierComparison.Equal; + return 1 /* Equal */; } // if moduleSpecifier1 (ms1) is a substring of ms2, then it is better if (moduleSpecifier2.indexOf(moduleSpecifier1) === 0) { - return ModuleSpecifierComparison.Better; + return 0 /* Better */; } if (moduleSpecifier1.indexOf(moduleSpecifier2) === 0) { - return ModuleSpecifierComparison.Worse; + return 2 /* Worse */; } // if both are relative paths, and ms1 has fewer levels, then it is better if (ts.isExternalModuleNameRelative(moduleSpecifier1) && ts.isExternalModuleNameRelative(moduleSpecifier2)) { @@ -90352,13 +90655,13 @@ var ts; var moduleSpecifier1LevelCount = (moduleSpecifier1.match(regex) || []).length; var moduleSpecifier2LevelCount = (moduleSpecifier2.match(regex) || []).length; return moduleSpecifier1LevelCount < moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Better + ? 0 /* Better */ : moduleSpecifier1LevelCount === moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Equal - : ModuleSpecifierComparison.Worse; + ? 1 /* Equal */ + : 2 /* Worse */; } // the equal cases include when the two specifiers are not comparable. - return ModuleSpecifierComparison.Equal; + return 1 /* Equal */; }; return ImportCodeActionMap; }()); @@ -91130,6 +91433,574 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + ], + getCodeActions: getActionsForAddExplicitTypeAnnotation + }); + function getActionsForAddExplicitTypeAnnotation(_a) { + var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var writer; + if (ts.isInJavaScriptFile(token)) { + return undefined; + } + switch (token.kind) { + case 71 /* Identifier */: + case 24 /* DotDotDotToken */: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + // Allowed + break; + default: + return undefined; + } + var containingFunction = ts.getContainingFunction(token); + var checker = program.getTypeChecker(); + switch (errorCode) { + // Variable and Property declarations + 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: + return getCodeActionForVariableDeclaration(token.parent); + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: + return getCodeActionForVariableUsage(token); + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessor(containingFunction)) { + return getCodeActionForSetAccessor(containingFunction); + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + return getCodeActionForParameters(token.parent); + // 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: + return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined; + } + return undefined; + function getCodeActionForVariableDeclaration(declaration) { + if (!ts.isIdentifier(declaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(declaration.name); + var typeString = type && typeToString(type, declaration); + if (!typeString) { + return undefined; + } + return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), ": " + typeString); + } + function getCodeActionForVariableUsage(token) { + var symbol = checker.getSymbolAtLocation(token); + return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration); + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 152 /* Constructor */: + return true; + case 186 /* FunctionExpression */: + return !!declaration.name; + } + return false; + } + function getCodeActionForParameters(parameterDeclaration) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return undefined; + } + var types = inferTypeForParametersFromUsage(containingFunction) || + ts.map(containingFunction.parameters, function (p) { return ts.isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name); }); + if (!types) { + return undefined; + } + var textChanges = ts.zipWith(containingFunction.parameters, types, function (parameter, type) { + if (type && !parameter.type && !parameter.initializer) { + var typeString = typeToString(type, containingFunction); + return typeString ? { + span: { start: parameter.end, length: 0 }, + newText: ": " + typeString + } : undefined; + } + }).filter(function (c) { return !!c; }); + return textChanges.length ? [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: textChanges + }] + }] : undefined; + } + function getCodeActionForSetAccessor(setAccessorDeclaration) { + var setAccessorParameter = setAccessorDeclaration.parameters[0]; + if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) || + inferTypeForVariableFromUsage(setAccessorParameter.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), ": " + typeString); + } + function getCodeActionForGetAccessor(getAccessorDeclaration) { + if (!ts.isIdentifier(getAccessorDeclaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + var closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, 20 /* CloseParenToken */); + return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), ": " + typeString); + } + function createCodeActions(name, start, typeString) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_type_of_0_from_usage), [name]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: start, length: 0 }, + newText: typeString + }] + }] + }]; + } + function getReferences(token) { + var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), token.getSourceFile(), token.getStart()); + ts.Debug.assert(!!references, "Found no references!"); + ts.Debug.assert(references.length === 1, "Found more references than expected"); + return ts.map(references[0].references, function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false); }); + } + function inferTypeForVariableFromUsage(token) { + return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken); + } + function inferTypeForParametersFromUsage(containingFunction) { + switch (containingFunction.kind) { + case 152 /* Constructor */: + case 186 /* FunctionExpression */: + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + var isConstructor = containingFunction.kind === 152 /* Constructor */; + var searchToken = isConstructor ? + getFirstChildOfKind(containingFunction, sourceFile, 123 /* ConstructorKeyword */) : + containingFunction.name; + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken); + } + } + } + function getTypeAccessiblityWriter() { + if (!writer) { + var str_1 = ""; + var typeIsAccessible_1 = true; + var writeText = function (text) { return str_1 += text; }; + writer = { + string: function () { return typeIsAccessible_1 ? str_1 : undefined; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + writeLine: function () { return str_1 += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { str_1 = ""; typeIsAccessible_1 = true; }, + trackSymbol: function (symbol, declaration, meaning) { + if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { + typeIsAccessible_1 = false; + } + }, + reportInaccessibleThisError: function () { typeIsAccessible_1 = false; }, + reportPrivateInBaseOfClassExpression: function () { typeIsAccessible_1 = false; }, + }; + } + writer.clear(); + return writer; + } + function typeToString(type, enclosingDeclaration) { + var writer = getTypeAccessiblityWriter(); + checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); + return writer.string(); + } + function getFirstChildOfKind(node, sourcefile, kind) { + for (var _i = 0, _a = node.getChildren(sourcefile); _i < _a.length; _i++) { + var child = _a[_i]; + if (child.kind === kind) + return child; + } + return undefined; + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypeFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return getTypeFromUsageContext(usageContext, checker); + } + InferFromReference.inferTypeFromReferences = inferTypeFromReferences; + function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { + if (declaration.parameters) { + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var isConstructor = declaration.kind === 152 /* Constructor */; + var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; + if (callContexts) { + var paramTypes = []; + for (var parameterIndex = 0; parameterIndex < declaration.parameters.length; parameterIndex++) { + var types = []; + var isRestParameter_1 = ts.isRestParameter(declaration.parameters[parameterIndex]); + for (var _a = 0, callContexts_1 = callContexts; _a < callContexts_1.length; _a++) { + var callContext = callContexts_1[_a]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter_1) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + paramTypes[parameterIndex] = isRestParameter_1 ? checker.createArrayType(type) : type; + } + } + return paramTypes; + } + } + return undefined; + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 193 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 192 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 194 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 257 /* CaseClause */: + case 258 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 181 /* CallExpression */: + case 182 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 179 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 180 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isPartOfExpression(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + usageContext.isNumber = true; + break; + case 37 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 40 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: + // ShiftOperator + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 48 /* AmpersandToken */: + case 49 /* BarToken */: + case 50 /* CaretToken */: + // CompoundAssignmentOperator + case 60 /* MinusEqualsToken */: + case 62 /* AsteriskAsteriskEqualsToken */: + case 61 /* AsteriskEqualsToken */: + case 63 /* SlashEqualsToken */: + case 64 /* PercentEqualsToken */: + case 68 /* AmpersandEqualsToken */: + case 69 /* BarEqualsToken */: + case 70 /* CaretEqualsToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 38 /* MinusToken */: + // RelationalOperator + case 27 /* LessThanToken */: + case 30 /* LessThanEqualsToken */: + case 29 /* GreaterThanToken */: + case 31 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 272 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 59 /* PlusEqualsToken */: + case 37 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 272 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 84 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 262178 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 58 /* EqualsToken */: + case 32 /* EqualsEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 92 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 54 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 226 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 53 /* AmpersandAmpersandToken */: + case 26 /* CommaToken */: + case 93 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 181 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 84 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function getTypeFromUsageContext(usageContext, checker) { + if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { + return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); + } + else if (usageContext.isNumber) { + return checker.getNumberType(); + } + else if (usageContext.isString) { + return checker.getStringType(); + } + else if (usageContext.candidateTypes) { + return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), /*subtypeReduction*/ true)); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); + var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + return checker.createPromiseType(types.length ? checker.getUnionType(types, /*subtypeReduction*/ true) : checker.getAnyType()); + } + 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) { + var members_4 = 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); + members_4.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.numberIndexContext) { + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); + } + return checker.createAnonymousType(/*symbol*/ undefined, members_4, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + return undefined; + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = getTypeFromUsageContext(callContext.returnType, checker); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 8192 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return usageContext && usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/// /// /// /// @@ -91144,6 +92015,7 @@ var ts; /// /// /// +/// /* @internal */ var ts; (function (ts) { @@ -91297,7 +92169,8 @@ var ts; switch (assignmentBinaryExpression.right.kind) { case 186 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); copyComments(assignmentBinaryExpression, method); return method; @@ -91314,7 +92187,8 @@ var ts; var expression = arrowFunctionBody; bodyBlock = ts.createBlock([ts.createReturn(expression)]); } - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); copyComments(assignmentBinaryExpression, method); return method; @@ -91359,7 +92233,8 @@ var ts; if (initializer.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; @@ -91369,11 +92244,15 @@ var ts; if (node.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } } })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); @@ -91506,7 +92385,7 @@ var ts; Messages.FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); Messages.CannotExtractIdentifier = createMessage("Select more than a single identifier."); Messages.CannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); - Messages.CannotCombineWritesAndReturns = createMessage("Cannot combine writes and returns"); + Messages.CannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); Messages.CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); Messages.CannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); @@ -91694,7 +92573,7 @@ var ts; permittedJumps = 0 /* None */; break; case 207 /* Block */: - if (node.parent && node.parent.kind === 224 /* TryStatement */ && node.finallyBlock === node) { + if (node.parent && node.parent.kind === 224 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } @@ -91791,7 +92670,10 @@ var ts; // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class var containingClass = ts.getContainingClass(current); if (containingClass) { - return [containingClass]; + var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration); + return containingFunction + ? [containingFunction, containingClass] + : [containingClass]; } } var start = current; @@ -91817,14 +92699,15 @@ var ts; return scopes; } function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope; + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); context.cancellationToken.throwIfCancellationRequested(); - return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); } function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope; + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); context.cancellationToken.throwIfCancellationRequested(); var expression = ts.isExpression(target) ? target @@ -91942,7 +92825,7 @@ var ts; })(SpecialScope || (SpecialScope = {})); function getUniqueName(baseName, fileText) { var nameText = baseName; - for (var i = 1; fileText.indexOf(nameText) !== -1; i++) { + for (var i = 1; ts.stringContains(fileText, nameText); i++) { nameText = baseName + "_" + i; } return nameText; @@ -91951,7 +92834,7 @@ var ts; * Result of 'extractRange' operation for a specific scope. * Stores either a list of changes that should be applied to extract a range or a list of errors */ - function extractFunctionInScope(node, scope, _a, range, context) { + function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted function @@ -91997,9 +92880,10 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType); + returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); } - var _b = transformFunctionBody(node, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + ts.suppressLeadingAndTrailingTrivia(body); var newFunction; if (ts.isClassLike(scope)) { // always create private method in TypeScript files @@ -92025,7 +92909,10 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); } else { - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { + prefix: ts.isLineBreak(file.text.charCodeAt(scope.getLastToken().pos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter, + suffix: context.newLineCharacter + }); } var newNodes = []; // replace range with function call @@ -92038,33 +92925,89 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { call = ts.createAwait(call); } - if (writes) { + if (exposedVariableDeclarations.length && !writes) { + // No need to mix declarations and writes. + // How could any variables be exposed if there's a return statement? + ts.Debug.assert(!returnValueProperty); + ts.Debug.assert(!(range.facts & RangeFacts.HasReturn)); + if (exposedVariableDeclarations.length === 1) { + // Declaring exactly one variable: let x = newFunction(); + var variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns + variableDeclaration.parent.flags))); + } + else { + // Declaring multiple variables / return properties: + // let {x, y} = newFunction(); + var bindingElements = []; + var typeElements = []; + var commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + var sawExplicitType = false; + for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { + var variableDeclaration = exposedVariableDeclarations_1[_i]; + bindingElements.push(ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, + /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); + // Being returned through an object literal will have widened the type. + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + typeElements.push(ts.createPropertySignature( + /*modifiers*/ undefined, + /*name*/ variableDeclaration.symbol.name, + /*questionToken*/ undefined, + /*type*/ variableType, + /*initializer*/ undefined)); + sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined; + if (typeLiteral) { + ts.setEmitFlags(typeLiteral, 1 /* SingleLine */); + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), + /*type*/ typeLiteral, + /*initializer*/ call)], commonNodeFlags))); + } + } + else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping. + for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) { + var variableDeclaration = exposedVariableDeclarations_2[_c]; + var flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */) { + flags = (flags & ~2 /* Const */) | 1 /* Let */; + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags))); + } + } if (returnValueProperty) { // has both writes and return, need to create variable declaration to hold return value; newNodes.push(ts.createVariableStatement( - /*modifiers*/ undefined, [ts.createVariableDeclaration(returnValueProperty, ts.createKeywordTypeNode(119 /* AnyKeyword */))])); + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */))); } - var assignments = getPropertyAssignmentsForWrites(writes); + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (returnValueProperty) { assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); } // propagate writes back if (assignments.length === 1) { - if (returnValueProperty) { - newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); - } - else { - newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58 /* EqualsToken */, call))); - if (range.facts & RangeFacts.HasReturn) { - newNodes.push(ts.createReturn()); - } + // We would only have introduced a return value property if there had been + // other assignments to make. + ts.Debug.assert(!returnValueProperty); + newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); } } else { // emit e.g. // { a, b, __return } = newFunction(a, b); // return __return; - newNodes.push(ts.createStatement(ts.createBinary(ts.createObjectLiteral(assignments), 58 /* EqualsToken */, call))); + newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call))); if (returnValueProperty) { newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); } @@ -92081,20 +93024,28 @@ var ts; newNodes.push(call); } } - if (isReadonlyArray(range.range)) { - changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes, { - nodeSeparator: context.newLineCharacter, - suffix: context.newLineCharacter // insert newline only when replacing statements - }); - } - else { - changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); - } + var replacementRange = isReadonlyArray(range.range) + ? { pos: ts.first(range.range).getStart(), end: ts.last(range.range).end } + : { pos: range.range.getStart(), end: range.range.end }; + changeTracker.replaceRangeWithNodes(context.file, replacementRange, newNodes, { nodeSeparator: context.newLineCharacter }); var edits = changeTracker.getChanges(); var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; var renameFilename = renameRange.getSourceFile().fileName; var renameLocation = getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === undefined) { + return undefined; + } + var clone = ts.getSynthesizedDeepClone(typeNode); + var withoutParens = clone; + while (ts.isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 139 /* UndefinedKeyword */; }) + ? clone + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(139 /* UndefinedKeyword */)]); + } } /** * Result of 'extractRange' operation for a specific scope. @@ -92109,8 +93060,9 @@ var ts; var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS ? undefined - : checker.typeToTypeNode(checker.getContextualType(node)); + : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); var initializer = transformConstantInitializer(node, substitutions); + ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); if (ts.isClassLike(scope)) { ts.Debug.assert(!isJS); // See CannotExtractToJSClass @@ -92131,7 +93083,7 @@ var ts; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, { suffix: context.newLineCharacter + context.newLineCharacter }); // Consume - changeTracker.replaceNodeWithNodes(context.file, node, [localReference], { nodeSeparator: context.newLineCharacter }); + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); } else { var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); @@ -92281,21 +93233,22 @@ var ts; return functionReference; } } - function transformFunctionBody(body, writes, substitutions, hasReturn) { - if (ts.isBlock(body) && !writes && substitutions.size === 0) { - // already block, no writes to propagate back, no substitutions - can use node as is + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) { + var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; + if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { + // already block, no declarations or writes to propagate back, no substitutions - can use node as is return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; } var returnValueProperty; var ignoreReturns = false; var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions - if (writes || substitutions.size) { + if (hasWritesOrVariableDeclarations || substitutions.size) { var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); - if (writes && !hasReturn && ts.isStatement(body)) { + if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) { // add return at the end to propagate writes back in case if control flow falls out of the function body // it is ok to know that range has at least one return since it we only allow unconditional returns - var assignments = getPropertyAssignmentsForWrites(writes); + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (assignments.length === 1) { rewrittenStatements.push(ts.createReturn(assignments[0].name)); } @@ -92309,8 +93262,8 @@ var ts; return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 219 /* ReturnStatement */ && writes) { - var assignments = getPropertyAssignmentsForWrites(writes); + if (!ignoreReturns && node.kind === 219 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { returnValueProperty = "__return"; @@ -92328,7 +93281,7 @@ var ts; var oldIgnoreReturns = ignoreReturns; ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node); var substitution = substitutions.get(ts.getNodeId(node).toString()); - var result = substitution ? substitution() : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); ignoreReturns = oldIgnoreReturns; return result; } @@ -92340,7 +93293,7 @@ var ts; : initializer; function visitor(node) { var substitution = substitutions.get(ts.getNodeId(node).toString()); - return substitution ? substitution() : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); } } function getStatementsOrClassElements(scope) { @@ -92375,8 +93328,8 @@ var ts; ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. var prevMember = undefined; var allProperties = true; - for (var _i = 0, members_4 = members; _i < members_4.length; _i++) { - var member = members_4[_i]; + for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { + var member = members_5[_i]; if (member.pos > maxPos) { return prevMember || members[0]; } @@ -92421,8 +93374,14 @@ var ts; } } } - function getPropertyAssignmentsForWrites(writes) { - return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); + var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + return variableAssignments === undefined + ? writeAssignments + : writeAssignments === undefined + ? variableAssignments + : variableAssignments.concat(writeAssignments); } function isReadonlyArray(v) { return ts.isArray(v); @@ -92455,6 +93414,9 @@ var ts; var functionErrorsPerScope = []; var constantErrorsPerScope = []; var visibleDeclarationsInExtractedRange = []; + var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID + var exposedVariableDeclarations = []; + var firstExposedNonVariableDeclaration = undefined; var expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) @@ -92493,7 +93455,6 @@ var ts; } var seenUsages = ts.createMap(); var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; - var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range; var inGenericContext = isInGenericContext(unmodifiedNode); collectUsages(target); @@ -92531,6 +93492,14 @@ var ts; // copy allTypeParameterUsages into all remaining scopes. ts.Debug.assert(i_1 === scopes.length); } + // If there are any declarations in the extracted block that are used in the same enclosing + // lexical scope, we can't move the extraction "up" as those declarations will become unreachable + if (visibleDeclarationsInExtractedRange.length) { + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) + ? scopes[0] + : ts.getEnclosingBlockScopeContainer(scopes[0]); + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } var _loop_8 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. @@ -92552,8 +93521,10 @@ var ts; } } }); - if (hasWrite && !isReadonlyArray(targetRange.range) && ts.isExpression(targetRange.range)) { - var diag = ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns); + // If an expression was extracted, then there shouldn't have been any variable declarations. + ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + var diag = ts.createDiagnosticForNode(targetRange.range, Messages.CannotWriteInExpression); functionErrorsPerScope[i].push(diag); constantErrorsPerScope[i].push(diag); } @@ -92562,16 +93533,16 @@ var ts; functionErrorsPerScope[i].push(diag); constantErrorsPerScope[i].push(diag); } + else if (firstExposedNonVariableDeclaration) { + var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.CannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } }; for (var i = 0; i < scopes.length; i++) { _loop_8(i); } - // If there are any declarations in the extracted block that are used in the same enclosing - // lexical scope, we can't move the extraction "up" as those declarations will become unreachable - if (visibleDeclarationsInExtractedRange.length) { - ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); - } - return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope }; + return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function hasTypeParameters(node) { return ts.isDeclarationWithTypeParameters(node) && node.typeParameters !== undefined && @@ -92605,7 +93576,7 @@ var ts; recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { - visibleDeclarationsInExtractedRange.push(node.symbol); + visibleDeclarationsInExtractedRange.push(node); } if (ts.isAssignmentExpression(node)) { // use 'write' as default usage for values @@ -92648,11 +93619,7 @@ var ts; } } function recordUsagebySymbol(identifier, usage, isTypeName) { - // If the identifier is both a property name and its value, we're only interested in its value - // (since the name is a declaration and will be included in the extracted range). - var symbol = identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier - ? checker.getShorthandAssignmentValueSymbol(identifier.parent) - : checker.getSymbolAtLocation(identifier); + var symbol = getSymbolReferencedByIdentifier(identifier); if (!symbol) { // cannot find symbol - do nothing return undefined; @@ -92736,37 +93703,52 @@ var ts; return; } // Otherwise check and recurse. - var sym = checker.getSymbolAtLocation(node); - if (sym && visibleDeclarationsInExtractedRange.some(function (d) { return d === sym; })) { - var diag = ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity); - for (var _i = 0, functionErrorsPerScope_2 = functionErrorsPerScope; _i < functionErrorsPerScope_2.length; _i++) { - var errors = functionErrorsPerScope_2[_i]; - errors.push(diag); + var sym = ts.isIdentifier(node) + ? getSymbolReferencedByIdentifier(node) + : checker.getSymbolAtLocation(node); + if (sym) { + var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; }); + if (decl) { + if (ts.isVariableDeclaration(decl)) { + var idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } + else { + // CONSIDER: this includes binding elements, which we could + // expose in the same way as variables. + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } } - for (var _a = 0, constantErrorsPerScope_2 = constantErrorsPerScope; _a < constantErrorsPerScope_2.length; _a++) { - var errors = constantErrorsPerScope_2[_a]; - errors.push(diag); - } - return true; - } - else { - ts.forEachChild(node, checkForUsedDeclarations); } + ts.forEachChild(node, checkForUsedDeclarations); + } + /** + * Return the symbol referenced by an identifier (even if it declares a different symbol). + */ + function getSymbolReferencedByIdentifier(identifier) { + // If the identifier is both a property name and its value, we're only interested in its value + // (since the name is a declaration and will be included in the extracted range). + return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); } function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { if (!symbol) { return undefined; } if (symbol.getDeclarations().some(function (d) { return d.parent === scopeDecl; })) { - return function () { return ts.createIdentifier(symbol.name); }; + return ts.createIdentifier(symbol.name); } var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode); if (prefix === undefined) { return undefined; } return isTypeNode - ? function () { return ts.createQualifiedName(prefix(), ts.createIdentifier(symbol.name)); } - : function () { return ts.createPropertyAccess(prefix(), symbol.name); }; + ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) + : ts.createPropertyAccess(prefix, symbol.name); } } function getParentNodeInSpan(node, file, span) { @@ -94402,7 +95384,7 @@ var ts; } function isNodeModulesFile(path) { var node_modulesFolderName = "/node_modules/"; - return path.indexOf(node_modulesFolderName) !== -1; + return ts.stringContains(path, node_modulesFolderName); } } function getRenameInfo(fileName, position) { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 1d798240595..4b897eb3548 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -162,7 +162,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.6"; - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -312,10 +312,12 @@ var ts; } ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { + var result = []; Debug.assert(arrayA.length === arrayB.length); for (var i = 0; i < arrayA.length; i++) { - callback(arrayA[i], arrayB[i], i); + result.push(callback(arrayA[i], arrayB[i], i)); } + return result; } ts.zipWith = zipWith; function zipToMap(keys, values) { @@ -434,22 +436,6 @@ var ts; return array; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var item = array_2[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var i = 0; i < array.length; i++) { @@ -500,8 +486,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -665,8 +651,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (predicate(v)) { return true; } @@ -691,8 +677,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + loop: for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -780,8 +766,8 @@ var ts; ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result += v[prop]; } return result; @@ -1081,8 +1067,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; @@ -1490,7 +1476,7 @@ var ts; } ts.getDirectoryPath = getDirectoryPath; function isUrl(path) { - return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + return path && !isRootedDiskPath(path) && stringContains(path, "://"); } ts.isUrl = isUrl; function pathIsRelative(path) { @@ -1719,8 +1705,12 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; function hasExtension(fileName) { - return getBaseFileName(fileName).indexOf(".") >= 0; + return stringContains(getBaseFileName(fileName), "."); } ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { @@ -3108,6 +3098,7 @@ var ts; Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), 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."), @@ -3435,6 +3426,7 @@ var ts; A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), 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}'."), @@ -3758,9 +3750,10 @@ var ts; Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), - JSDoc_augments_is_not_attached_to_a_class_declaration: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_augments_is_not_attached_to_a_class_declaration_8022", "JSDoc '@augments' is not attached to a class declaration."), - JSDoc_augments_0_does_not_match_the_extends_1_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023", "JSDoc '@augments {0}' does not match the 'extends {1}' clause."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), 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."), @@ -3792,7 +3785,7 @@ 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(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), - Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'."), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), @@ -3806,6 +3799,7 @@ var ts; Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'."), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), @@ -3814,6 +3808,8 @@ var ts; Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Infer_type_of_0_from_usage: diag(95009, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95009", "Infer type of '{0}' from usage."), + Infer_parameter_types_from_usage: diag(95010, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95010", "Infer parameter types from usage."), }; })(ts || (ts = {})); var ts; @@ -5168,27 +5164,14 @@ var ts; } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { - return isRestParameter(ts.lastOrUndefined(s.parameters)); + var last = ts.lastOrUndefined(s.parameters); + return last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; - function hasDeclaredRestParameter(s) { - return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); - } - ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 274 || - ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { - return true; - } - } - return isDeclaredRestParam(node); + return node.dotDotDotToken !== undefined; } ts.isRestParameter = isRestParameter; - function isDeclaredRestParam(node) { - return node && node.dotDotDotToken !== undefined; - } - ts.isDeclaredRestParam = isDeclaredRestParam; function getAssignmentTargetKind(node) { var parent = node.parent; while (true) { @@ -7115,27 +7098,35 @@ var ts; if (!declaration) { return undefined; } - if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143) { - return declaration.name.right; - } - if (declaration.kind === 194) { - var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { - case 1: - case 4: - case 5: - case 3: - return expr.left.name; - default: - return undefined; + switch (declaration.kind) { + case 284: + case 279: { + var name = declaration.name; + if (name.kind === 143) { + return name.right; + } + break; + } + case 194: { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + default: + return undefined; + } + } + case 283: + return getNameOfJSDocTypedef(declaration); + case 243: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; } } - else if (declaration.kind === 283) { - return getNameOfJSDocTypedef(declaration); - } - else { - return declaration.name; - } + return declaration.name; } ts.getNameOfDeclaration = getNameOfDeclaration; function getJSDocParameterTags(param) { @@ -7202,6 +7193,11 @@ var ts; var tags = getJSDocTags(node); return ts.find(tags, function (doc) { return doc.kind === kind; }); } + function getAllJSDocTagsOfKind(node, kind) { + var tags = getJSDocTags(node); + return ts.filter(tags, function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); (function (ts) { function isNumericLiteral(node) { @@ -8436,6 +8432,14 @@ var ts; return node.kind >= 276 && node.kind <= 285; } ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 154; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 153; + } + ts.isGetAccessor = isGetAccessor; function hasJSDocNodes(node) { return !!node.jsDoc && node.jsDoc.length > 0; } @@ -14575,6 +14579,7 @@ var ts; if (tagName) { switch (tagName.escapedText) { case "augments": + case "extends": tag = parseAugmentsTag(atToken, tagName); break; case "class": @@ -14859,7 +14864,7 @@ var ts; if (typeExpression && typeExpression.type.kind === 164) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); } @@ -15084,8 +15089,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var node = array_7[_i]; visitNode(node); } } @@ -15157,8 +15162,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } return; @@ -17991,7 +17996,7 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : withoutAtTypePrefix; } @@ -18513,20 +18518,20 @@ var ts; function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, throttleLimit, log) { var _this = _super.call(this, ts.sys, globalTypingsCacheLocation, typingSafeListLocation ? ts.toPath(typingSafeListLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), typesMapLocation ? ts.toPath(typesMapLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typesMap.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this; _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0]); - if (_this.npmPath.indexOf(" ") !== -1 && _this.npmPath[0] !== "\"") { + if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") { _this.npmPath = "\"" + _this.npmPath + "\""; } if (_this.log.isEnabled()) { _this.log.writeLine("Process id: " + process.pid); _this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)"); } - (_this.execSync = require("child_process").execSync); + (_this.nodeExecSync = require("child_process").execSync); _this.ensurePackageDirectoryExists(globalTypingsCacheLocation); try { if (_this.log.isEnabled()) { _this.log.writeLine("Updating " + TypesRegistryPackageName + " npm package..."); } - _this.execSync(_this.npmPath + " install --ignore-scripts " + TypesRegistryPackageName, { cwd: globalTypingsCacheLocation, stdio: "ignore" }); + _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + TypesRegistryPackageName, { cwd: globalTypingsCacheLocation }); if (_this.log.isEnabled()) { _this.log.writeLine("Updated " + TypesRegistryPackageName + " npm package"); } @@ -18574,22 +18579,29 @@ var ts; } var command = this.npmPath + " install --ignore-scripts " + args.join(" ") + " --save-dev --user-agent=\"typesInstaller/" + ts.version + "\""; var start = Date.now(); - var stdout; - var stderr; - var hasError = false; - try { - stdout = this.execSync(command, { cwd: cwd }); - } - catch (e) { - stdout = e.stdout; - stderr = e.stderr; - hasError = true; - } + var hasError = this.execSyncAndLog(command, { cwd: cwd }); if (this.log.isEnabled()) { - this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms" + ts.sys.newLine + "stdout: " + (stdout && stdout.toString()) + ts.sys.newLine + "stderr: " + (stderr && stderr.toString())); + this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms"); } onRequestCompleted(!hasError); }; + NodeTypingsInstaller.prototype.execSyncAndLog = function (command, options) { + if (this.log.isEnabled()) { + this.log.writeLine("Exec: " + command); + } + try { + var stdout = this.nodeExecSync(command, __assign({}, options, { encoding: "utf-8" })); + if (this.log.isEnabled()) { + this.log.writeLine(" Succeeded. stdout:" + indent(ts.sys.newLine, stdout)); + } + return false; + } + catch (error) { + var stdout = error.stdout, stderr = error.stderr; + this.log.writeLine(" Failed. stdout:" + indent(ts.sys.newLine, stdout) + ts.sys.newLine + " stderr:" + indent(ts.sys.newLine, stderr)); + return true; + } + }; return NodeTypingsInstaller; }(typingsInstaller.TypingsInstaller)); typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller; @@ -18612,6 +18624,9 @@ var ts; }); var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, 5, log); installer.listen(); + function indent(newline, string) { + return newline + " " + string.replace(/\r?\n/, newline + " "); + } })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {}));