diff --git a/Gulpfile.ts b/Gulpfile.ts index 32fbf2c43e0..d856254296e 100644 --- a/Gulpfile.ts +++ b/Gulpfile.ts @@ -131,6 +131,7 @@ const es2017LibrarySource = [ "es2017.object.d.ts", "es2017.sharedmemory.d.ts", "es2017.string.d.ts", + "es2017.intl.d.ts", ]; const es2017LibrarySourceMap = es2017LibrarySource.map(function(source) { @@ -935,7 +936,7 @@ gulp.task(loggedIOJsPath, /*help*/ false, [], (done) => { const temp = path.join(builtLocalDirectory, "temp"); mkdirP(temp, (err) => { if (err) { console.error(err); done(err); process.exit(1); } - exec(host, [LKGCompiler, "--types --outdir", temp, loggedIOpath], () => { + exec(host, [LKGCompiler, "--types", "--target es5", "--lib es5", "--outdir", temp, loggedIOpath], () => { fs.renameSync(path.join(temp, "/harness/loggedIO.js"), loggedIOJsPath); del(temp).then(() => done(), done); }, done); @@ -946,7 +947,13 @@ const instrumenterPath = path.join(harnessDirectory, "instrumenter.ts"); const instrumenterJsPath = path.join(builtLocalDirectory, "instrumenter.js"); gulp.task(instrumenterJsPath, /*help*/ false, [servicesFile], () => { const settings: tsc.Settings = getCompilerSettings({ - outFile: instrumenterJsPath + outFile: instrumenterJsPath, + target: "es5", + lib: [ + "es6", + "dom", + "scripthost" + ] }, /*useBuiltCompiler*/ true); return gulp.src(instrumenterPath) .pipe(newer(instrumenterJsPath)) diff --git a/Jakefile.js b/Jakefile.js index 807546d59f8..577ade2ef69 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -172,7 +172,8 @@ var es2016LibrarySourceMap = es2016LibrarySource.map(function (source) { var es2017LibrarySource = [ "es2017.object.d.ts", "es2017.sharedmemory.d.ts", - "es2017.string.d.ts" + "es2017.string.d.ts", + "es2017.intl.d.ts" ]; var es2017LibrarySourceMap = es2017LibrarySource.map(function (source) { diff --git a/lib/cancellationToken.js b/lib/cancellationToken.js index 0e37b0689e0..ec9453bb00c 100644 --- a/lib/cancellationToken.js +++ b/lib/cancellationToken.js @@ -69,3 +69,5 @@ function createCancellationToken(args) { } } module.exports = createCancellationToken; + +//# sourceMappingURL=cancellationToken.js.map diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 80e09b844cb..9848b920637 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -1406,6 +1406,14 @@ interface ArrayBuffer { slice(begin: number, end?: number): ArrayBuffer; } +/** + * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. + */ +interface ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} +type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; + interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; @@ -1417,7 +1425,7 @@ interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1559,7 +1567,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; + new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1576,7 +1584,7 @@ interface Int8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1819,7 +1827,7 @@ interface Int8ArrayConstructor { readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1860,7 +1868,7 @@ interface Uint8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2104,7 +2112,7 @@ interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2145,7 +2153,7 @@ interface Uint8ClampedArray { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2389,7 +2397,7 @@ interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2429,7 +2437,7 @@ interface Int16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2673,7 +2681,7 @@ interface Int16ArrayConstructor { readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2714,7 +2722,7 @@ interface Uint16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2958,7 +2966,7 @@ interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2998,7 +3006,7 @@ interface Int32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3242,7 +3250,7 @@ interface Int32ArrayConstructor { readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3282,7 +3290,7 @@ interface Uint32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3526,7 +3534,7 @@ interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3566,7 +3574,7 @@ interface Float32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3810,7 +3818,7 @@ interface Float32ArrayConstructor { readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3851,7 +3859,7 @@ interface Float64Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -4095,7 +4103,7 @@ interface Float64ArrayConstructor { readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. diff --git a/lib/lib.es2015.iterable.d.ts b/lib/lib.es2015.iterable.d.ts index 1fe1a0e0ca1..551698607ca 100644 --- a/lib/lib.es2015.iterable.d.ts +++ b/lib/lib.es2015.iterable.d.ts @@ -52,17 +52,17 @@ interface Array { [Symbol.iterator](): IterableIterator; /** - * Returns an array of key, value pairs for every entry in the array + * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** - * Returns an list of keys in the array + * Returns an iterable of keys in the array */ keys(): IterableIterator; /** - * Returns an list of values in the array + * Returns an iterable of values in the array */ values(): IterableIterator; } @@ -86,21 +86,21 @@ interface ArrayConstructor { } interface ReadonlyArray { - /** Iterator */ + /** Iterator of values in the array. */ [Symbol.iterator](): IterableIterator; /** - * Returns an array of key, value pairs for every entry in the array + * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** - * Returns an list of keys in the array + * Returns an iterable of keys in the array */ keys(): IterableIterator; /** - * Returns an list of values in the array + * Returns an iterable of values in the array */ values(): IterableIterator; } @@ -111,9 +111,42 @@ interface IArguments { } interface Map { + /** Returns an iterable of entries in the map. */ [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface ReadonlyMap { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ values(): IterableIterator; } @@ -128,9 +161,40 @@ interface WeakMapConstructor { } interface Set { + /** Iterates over values in the set. */ [Symbol.iterator](): IterableIterator; + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ entries(): IterableIterator<[T, T]>; + /** + * Despite its name, returns an iterable of the values in the set, + */ keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface ReadonlySet { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ values(): IterableIterator; } diff --git a/lib/lib.es2015.proxy.d.ts b/lib/lib.es2015.proxy.d.ts index 29b12d91e24..440897038ef 100644 --- a/lib/lib.es2015.proxy.d.ts +++ b/lib/lib.es2015.proxy.d.ts @@ -23,7 +23,7 @@ interface ProxyHandler { setPrototypeOf? (target: T, v: any): boolean; isExtensible? (target: T): boolean; preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; has? (target: T, p: PropertyKey): boolean; get? (target: T, p: PropertyKey, receiver: any): any; set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; diff --git a/lib/lib.es2016.full.d.ts b/lib/lib.es2016.full.d.ts index 737357fef6d..a22ca2e9d80 100644 --- a/lib/lib.es2016.full.d.ts +++ b/lib/lib.es2016.full.d.ts @@ -21,6 +21,1830 @@ and limitations under the License. /// /// +declare type PropertyKey = string | number | symbol; + +interface Array { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (this: void, value: T, index: number, obj: Array) => boolean): T | undefined; + find(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): T | undefined; + find(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean): number; + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; + findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): this; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U): Array; + from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; + from(arrayLike: ArrayLike, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; + + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +interface DateConstructor { + new (value: Date): Date; +} + +interface Function { + /** + * Returns the name of the function. Function names are read-only and can not be changed. + */ + readonly name: string; +} + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or −0, the result is +0. + */ + hypot(...values: number[] ): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; +} + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍−‍16. + */ + readonly EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + readonly MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n − 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). + */ + readonly MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface Object { + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source The source object from which to copy properties. + */ + assign(target: T, source: U): T & U; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V): T & U & V; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + * @param source3 The third source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ + assign(target: object, ...sources: any[]): any; + + /** + * Returns an array of all symbol properties found directly on object o. + * @param o Object to retrieve the symbols from. + */ + getOwnPropertySymbols(o: any): symbol[]; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + */ + setPrototypeOf(o: any, proto: object | null): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not + * inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript + * object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor + * property. + */ + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; +} + +interface ReadonlyArray { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean): T | undefined; + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: undefined): T | undefined; + find(predicate: (this: Z, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: Z): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean): number; + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; + findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; +} + +interface RegExp { + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + readonly flags: string; + + /** + * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular + * expression. Default is false. Read-only. + */ + readonly sticky: boolean; + + /** + * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular + * expression. Default is false. Read-only. + */ + readonly unicode: boolean; +} + +interface RegExpConstructor { + new (pattern: RegExp, flags?: string): RegExp; + (pattern: RegExp, flags?: string): RegExp; +} + +interface String { + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number | undefined; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form?: string): string; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; + + /** + * Returns an HTML anchor element and sets the name attribute to the text value + * @param name + */ + anchor(name: string): string; + + /** Returns a HTML element */ + big(): string; + + /** Returns a HTML element */ + blink(): string; + + /** Returns a HTML element */ + bold(): string; + + /** Returns a HTML element */ + fixed(): string; + + /** Returns a HTML element and sets the color attribute value */ + fontcolor(color: string): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: number): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: string): string; + + /** Returns an HTML element */ + italics(): string; + + /** Returns an HTML element and sets the href attribute value */ + link(url: string): string; + + /** Returns a HTML element */ + small(): string; + + /** Returns a HTML element */ + strike(): string; + + /** Returns a HTML element */ + sub(): string; + + /** Returns a HTML element */ + sup(): string; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; + readonly size: number; +} + +interface MapConstructor { + new (): Map; + new (entries?: [K, V][]): Map; + readonly prototype: Map; +} +declare var Map: MapConstructor; + +interface ReadonlyMap { + forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + readonly size: number; +} + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (entries?: [K, V][]): WeakMap; + readonly prototype: WeakMap; +} +declare var WeakMap: WeakMapConstructor; + +interface Set { + add(value: T): this; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface SetConstructor { + new (): Set; + new (values?: T[]): Set; + readonly prototype: Set; +} +declare var Set: SetConstructor; + +interface ReadonlySet { + forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface WeakSet { + add(value: T): this; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (values?: T[]): WeakSet; + readonly prototype: WeakSet; +} +declare var WeakSet: WeakSetConstructor; + + +interface Generator extends Iterator { } + +interface GeneratorFunction { + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + new (...args: any[]): Generator; + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + (...args: any[]): Generator; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: Generator; +} + +interface GeneratorFunctionConstructor { + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): GeneratorFunction; + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + (...args: string[]): GeneratorFunction; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: GeneratorFunction; +} +declare var GeneratorFunction: GeneratorFunctionConstructor; + + +/// + +interface SymbolConstructor { + /** + * A method that returns the default iterator for an object. Called by the semantics of the + * for-of statement. + */ + readonly iterator: symbol; +} + +interface IteratorResult { + done: boolean; + value: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +interface IterableIterator extends Iterator { + [Symbol.iterator](): IterableIterator; +} + +interface Array { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface ArrayConstructor { + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U): Array; + from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; + from(iterable: Iterable, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): Array; +} + +interface ReadonlyArray { + /** Iterator of values in the array. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface Map { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface ReadonlyMap { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface MapConstructor { + new (iterable: Iterable<[K, V]>): Map; +} + +interface WeakMap { } + +interface WeakMapConstructor { + new (iterable: Iterable<[K, V]>): WeakMap; +} + +interface Set { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface ReadonlySet { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface SetConstructor { + new (iterable: Iterable): Set; +} + +interface WeakSet { } + +interface WeakSetConstructor { + new (iterable: Iterable): WeakSet; +} + +interface Promise { } + +interface PromiseConstructor { + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: Iterable>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: Iterable>): Promise; +} + +declare namespace Reflect { + function enumerate(target: object): IterableIterator; +} + +interface String { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int8ArrayConstructor { + new (elements: Iterable): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int8Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; + + from(arrayLike: Iterable): Int8Array; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ArrayConstructor { + new (elements: Iterable): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; + + from(arrayLike: Iterable): Uint8Array; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ClampedArrayConstructor { + new (elements: Iterable): Uint8ClampedArray; + + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; + + from(arrayLike: Iterable): Uint8ClampedArray; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int16ArrayConstructor { + new (elements: Iterable): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int16Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; + + from(arrayLike: Iterable): Int16Array; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint16ArrayConstructor { + new (elements: Iterable): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint16Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; + + from(arrayLike: Iterable): Uint16Array; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int32ArrayConstructor { + new (elements: Iterable): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; + + from(arrayLike: Iterable): Int32Array; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint32ArrayConstructor { + new (elements: Iterable): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; + + from(arrayLike: Iterable): Uint32Array; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float32ArrayConstructor { + new (elements: Iterable): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; + + from(arrayLike: Iterable): Float32Array; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float64ArrayConstructor { + new (elements: Iterable): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float64Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; + + from(arrayLike: Iterable): Float64Array; +} + + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Promise; + + /** + * Creates a new Promise. + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: (T | PromiseLike)[]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: (T | PromiseLike)[]): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; +} + +declare var Promise: PromiseConstructor; + +interface ProxyHandler { + getPrototypeOf? (target: T): object | null; + setPrototypeOf? (target: T, v: any): boolean; + isExtensible? (target: T): boolean; + preventExtensions? (target: T): boolean; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; + has? (target: T, p: PropertyKey): boolean; + get? (target: T, p: PropertyKey, receiver: any): any; + set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; + deleteProperty? (target: T, p: PropertyKey): boolean; + defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; + enumerate? (target: T): PropertyKey[]; + ownKeys? (target: T): PropertyKey[]; + apply? (target: T, thisArg: any, argArray?: any): any; + construct? (target: T, argArray: any, newTarget?: any): object; +} + +interface ProxyConstructor { + revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; + new (target: T, handler: ProxyHandler): T; +} +declare var Proxy: ProxyConstructor; + + +declare namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; + function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: object, propertyKey: PropertyKey): boolean; + function get(target: object, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: object): object; + function has(target: object, propertyKey: PropertyKey): boolean; + function isExtensible(target: object): boolean; + function ownKeys(target: object): Array; + function preventExtensions(target: object): boolean; + function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: object, proto: any): boolean; +} + + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): symbol; +} + +interface SymbolConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Symbol; + + /** + * Returns a new unique Symbol value. + * @param description Description of the new Symbol object. + */ + (description?: string | number): symbol; + + /** + * Returns a Symbol object from the global symbol registry matching the given key if found. + * Otherwise, returns a new symbol with this key. + * @param key key to search for. + */ + for(key: string): symbol; + + /** + * Returns a key from the global symbol registry matching the given Symbol if found. + * Otherwise, returns a undefined. + * @param sym Symbol to find the key for. + */ + keyFor(sym: symbol): string | undefined; +} + +declare var Symbol: SymbolConstructor; + +/// + +interface SymbolConstructor { + /** + * A method that determines if a constructor object recognizes an object as one of the + * constructor’s instances. Called by the semantics of the instanceof operator. + */ + readonly hasInstance: symbol; + + /** + * A Boolean value that if true indicates that an object should flatten to its array elements + * by Array.prototype.concat. + */ + readonly isConcatSpreadable: symbol; + + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.match method. + */ + readonly match: symbol; + + /** + * A regular expression method that replaces matched substrings of a string. Called by the + * String.prototype.replace method. + */ + readonly replace: symbol; + + /** + * A regular expression method that returns the index within a string that matches the + * regular expression. Called by the String.prototype.search method. + */ + readonly search: symbol; + + /** + * A function valued property that is the constructor function that is used to create + * derived objects. + */ + readonly species: symbol; + + /** + * A regular expression method that splits a string at the indices that match the regular + * expression. Called by the String.prototype.split method. + */ + readonly split: symbol; + + /** + * A method that converts an object to a corresponding primitive value. + * Called by the ToPrimitive abstract operation. + */ + readonly toPrimitive: symbol; + + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + readonly toStringTag: symbol; + + /** + * An Object whose own property names are property names that are excluded from the 'with' + * environment bindings of the associated objects. + */ + readonly unscopables: symbol; +} + +interface Symbol { + readonly [Symbol.toStringTag]: "Symbol"; +} + +interface Array { + /** + * Returns an object whose properties have the value 'true' + * when they will be absent when used in a 'with' statement. + */ + [Symbol.unscopables](): { + copyWithin: boolean; + entries: boolean; + fill: boolean; + find: boolean; + findIndex: boolean; + keys: boolean; + values: boolean; + }; +} + +interface Date { + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "default"): string; + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "string"): string; + /** + * Converts a Date object to a number. + */ + [Symbol.toPrimitive](hint: "number"): number; + /** + * Converts a Date object to a string or number. + * + * @param hint The strings "number", "string", or "default" to specify what primitive to return. + * + * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". + * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". + */ + [Symbol.toPrimitive](hint: string): string | number; +} + +interface Map { + readonly [Symbol.toStringTag]: "Map"; +} + +interface WeakMap{ + readonly [Symbol.toStringTag]: "WeakMap"; +} + +interface Set { + readonly [Symbol.toStringTag]: "Set"; +} + +interface WeakSet { + readonly [Symbol.toStringTag]: "WeakSet"; +} + +interface JSON { + readonly [Symbol.toStringTag]: "JSON"; +} + +interface Function { + /** + * Determines whether the given value inherits from this function if this function was used + * as a constructor function. + * + * A constructor function can control which objects are recognized as its instances by + * 'instanceof' by overriding this method. + */ + [Symbol.hasInstance](value: any): boolean; +} + +interface GeneratorFunction { + readonly [Symbol.toStringTag]: "GeneratorFunction"; +} + +interface Math { + readonly [Symbol.toStringTag]: "Math"; +} + +interface Promise { + readonly [Symbol.toStringTag]: "Promise"; +} + +interface PromiseConstructor { + readonly [Symbol.species]: Function; +} + +interface RegExp { + /** + * Matches a string with this regular expression, and returns an array containing the results of + * that search. + * @param string A string to search within. + */ + [Symbol.match](string: string): RegExpMatchArray | null; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replaceValue A String object or string literal containing the text to replace for every + * successful match of this regular expression. + */ + [Symbol.replace](string: string, replaceValue: string): string; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replacer A function that returns the replacement text. + */ + [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the position beginning first substring match in a regular expression search + * using this regular expression. + * + * @param string The string to search within. + */ + [Symbol.search](string: string): number; + + /** + * Returns an array of substrings that were delimited by strings in the original input that + * match against this regular expression. + * + * If the regular expression contains capturing parentheses, then each time this + * regular expression matches, the results (including any undefined results) of the + * capturing parentheses are spliced. + * + * @param string string value to split + * @param limit if not undefined, the output array is truncated so that it contains no more + * than 'limit' elements. + */ + [Symbol.split](string: string, limit?: number): string[]; +} + +interface RegExpConstructor { + [Symbol.species](): RegExpConstructor; +} + +interface String { + /** + * Matches a string an object that supports being matched against, and returns an array containing the results of that search. + * @param matcher An object that supports being matched against. + */ + match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param searcher An object which supports searching within a string. + */ + search(searcher: { [Symbol.search](string: string): number; }): number; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param splitter An object that can split a string. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + readonly [Symbol.toStringTag]: "ArrayBuffer"; +} + +interface DataView { + readonly [Symbol.toStringTag]: "DataView"; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + readonly [Symbol.toStringTag]: "Int8Array"; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + readonly [Symbol.toStringTag]: "UInt8Array"; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + readonly [Symbol.toStringTag]: "Uint8ClampedArray"; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + readonly [Symbol.toStringTag]: "Int16Array"; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + readonly [Symbol.toStringTag]: "Uint16Array"; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + readonly [Symbol.toStringTag]: "Int32Array"; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + readonly [Symbol.toStringTag]: "Uint32Array"; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + readonly [Symbol.toStringTag]: "Float32Array"; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + readonly [Symbol.toStringTag]: "Float64Array"; +} + + ///////////////////////////// /// IE DOM APIs diff --git a/lib/lib.es2017.d.ts b/lib/lib.es2017.d.ts index a0d3a0aff28..64ebe606847 100644 --- a/lib/lib.es2017.d.ts +++ b/lib/lib.es2017.d.ts @@ -21,4 +21,5 @@ and limitations under the License. /// /// /// -/// \ No newline at end of file +/// +/// \ No newline at end of file diff --git a/lib/lib.es2017.full.d.ts b/lib/lib.es2017.full.d.ts index dae59bc9ae3..91bee6e9d56 100644 --- a/lib/lib.es2017.full.d.ts +++ b/lib/lib.es2017.full.d.ts @@ -22,6 +22,1831 @@ and limitations under the License. /// /// /// +/// + +declare type PropertyKey = string | number | symbol; + +interface Array { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (this: void, value: T, index: number, obj: Array) => boolean): T | undefined; + find(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): T | undefined; + find(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean): number; + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; + findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): this; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U): Array; + from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; + from(arrayLike: ArrayLike, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; + + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +interface DateConstructor { + new (value: Date): Date; +} + +interface Function { + /** + * Returns the name of the function. Function names are read-only and can not be changed. + */ + readonly name: string; +} + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or −0, the result is +0. + */ + hypot(...values: number[] ): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; +} + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍−‍16. + */ + readonly EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + readonly MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n − 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). + */ + readonly MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface Object { + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source The source object from which to copy properties. + */ + assign(target: T, source: U): T & U; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V): T & U & V; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + * @param source3 The third source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ + assign(target: object, ...sources: any[]): any; + + /** + * Returns an array of all symbol properties found directly on object o. + * @param o Object to retrieve the symbols from. + */ + getOwnPropertySymbols(o: any): symbol[]; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + */ + setPrototypeOf(o: any, proto: object | null): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not + * inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript + * object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor + * property. + */ + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; +} + +interface ReadonlyArray { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean): T | undefined; + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: undefined): T | undefined; + find(predicate: (this: Z, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: Z): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean): number; + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; + findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; +} + +interface RegExp { + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + readonly flags: string; + + /** + * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular + * expression. Default is false. Read-only. + */ + readonly sticky: boolean; + + /** + * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular + * expression. Default is false. Read-only. + */ + readonly unicode: boolean; +} + +interface RegExpConstructor { + new (pattern: RegExp, flags?: string): RegExp; + (pattern: RegExp, flags?: string): RegExp; +} + +interface String { + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number | undefined; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form?: string): string; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; + + /** + * Returns an HTML anchor element and sets the name attribute to the text value + * @param name + */ + anchor(name: string): string; + + /** Returns a HTML element */ + big(): string; + + /** Returns a HTML element */ + blink(): string; + + /** Returns a HTML element */ + bold(): string; + + /** Returns a HTML element */ + fixed(): string; + + /** Returns a HTML element and sets the color attribute value */ + fontcolor(color: string): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: number): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: string): string; + + /** Returns an HTML element */ + italics(): string; + + /** Returns an HTML element and sets the href attribute value */ + link(url: string): string; + + /** Returns a HTML element */ + small(): string; + + /** Returns a HTML element */ + strike(): string; + + /** Returns a HTML element */ + sub(): string; + + /** Returns a HTML element */ + sup(): string; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; + readonly size: number; +} + +interface MapConstructor { + new (): Map; + new (entries?: [K, V][]): Map; + readonly prototype: Map; +} +declare var Map: MapConstructor; + +interface ReadonlyMap { + forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + readonly size: number; +} + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (entries?: [K, V][]): WeakMap; + readonly prototype: WeakMap; +} +declare var WeakMap: WeakMapConstructor; + +interface Set { + add(value: T): this; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface SetConstructor { + new (): Set; + new (values?: T[]): Set; + readonly prototype: Set; +} +declare var Set: SetConstructor; + +interface ReadonlySet { + forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface WeakSet { + add(value: T): this; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (values?: T[]): WeakSet; + readonly prototype: WeakSet; +} +declare var WeakSet: WeakSetConstructor; + + +interface Generator extends Iterator { } + +interface GeneratorFunction { + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + new (...args: any[]): Generator; + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + (...args: any[]): Generator; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: Generator; +} + +interface GeneratorFunctionConstructor { + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): GeneratorFunction; + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + (...args: string[]): GeneratorFunction; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: GeneratorFunction; +} +declare var GeneratorFunction: GeneratorFunctionConstructor; + + +/// + +interface SymbolConstructor { + /** + * A method that returns the default iterator for an object. Called by the semantics of the + * for-of statement. + */ + readonly iterator: symbol; +} + +interface IteratorResult { + done: boolean; + value: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +interface IterableIterator extends Iterator { + [Symbol.iterator](): IterableIterator; +} + +interface Array { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface ArrayConstructor { + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U): Array; + from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; + from(iterable: Iterable, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): Array; +} + +interface ReadonlyArray { + /** Iterator of values in the array. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface Map { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface ReadonlyMap { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface MapConstructor { + new (iterable: Iterable<[K, V]>): Map; +} + +interface WeakMap { } + +interface WeakMapConstructor { + new (iterable: Iterable<[K, V]>): WeakMap; +} + +interface Set { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface ReadonlySet { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface SetConstructor { + new (iterable: Iterable): Set; +} + +interface WeakSet { } + +interface WeakSetConstructor { + new (iterable: Iterable): WeakSet; +} + +interface Promise { } + +interface PromiseConstructor { + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: Iterable>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: Iterable>): Promise; +} + +declare namespace Reflect { + function enumerate(target: object): IterableIterator; +} + +interface String { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int8ArrayConstructor { + new (elements: Iterable): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int8Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; + + from(arrayLike: Iterable): Int8Array; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ArrayConstructor { + new (elements: Iterable): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; + + from(arrayLike: Iterable): Uint8Array; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ClampedArrayConstructor { + new (elements: Iterable): Uint8ClampedArray; + + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; + + from(arrayLike: Iterable): Uint8ClampedArray; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int16ArrayConstructor { + new (elements: Iterable): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int16Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; + + from(arrayLike: Iterable): Int16Array; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint16ArrayConstructor { + new (elements: Iterable): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint16Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; + + from(arrayLike: Iterable): Uint16Array; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int32ArrayConstructor { + new (elements: Iterable): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; + + from(arrayLike: Iterable): Int32Array; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint32ArrayConstructor { + new (elements: Iterable): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; + + from(arrayLike: Iterable): Uint32Array; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float32ArrayConstructor { + new (elements: Iterable): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; + + from(arrayLike: Iterable): Float32Array; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float64ArrayConstructor { + new (elements: Iterable): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float64Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; + + from(arrayLike: Iterable): Float64Array; +} + + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Promise; + + /** + * Creates a new Promise. + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: (T | PromiseLike)[]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: (T | PromiseLike)[]): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; +} + +declare var Promise: PromiseConstructor; + +interface ProxyHandler { + getPrototypeOf? (target: T): object | null; + setPrototypeOf? (target: T, v: any): boolean; + isExtensible? (target: T): boolean; + preventExtensions? (target: T): boolean; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; + has? (target: T, p: PropertyKey): boolean; + get? (target: T, p: PropertyKey, receiver: any): any; + set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; + deleteProperty? (target: T, p: PropertyKey): boolean; + defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; + enumerate? (target: T): PropertyKey[]; + ownKeys? (target: T): PropertyKey[]; + apply? (target: T, thisArg: any, argArray?: any): any; + construct? (target: T, argArray: any, newTarget?: any): object; +} + +interface ProxyConstructor { + revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; + new (target: T, handler: ProxyHandler): T; +} +declare var Proxy: ProxyConstructor; + + +declare namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; + function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: object, propertyKey: PropertyKey): boolean; + function get(target: object, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: object): object; + function has(target: object, propertyKey: PropertyKey): boolean; + function isExtensible(target: object): boolean; + function ownKeys(target: object): Array; + function preventExtensions(target: object): boolean; + function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: object, proto: any): boolean; +} + + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): symbol; +} + +interface SymbolConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Symbol; + + /** + * Returns a new unique Symbol value. + * @param description Description of the new Symbol object. + */ + (description?: string | number): symbol; + + /** + * Returns a Symbol object from the global symbol registry matching the given key if found. + * Otherwise, returns a new symbol with this key. + * @param key key to search for. + */ + for(key: string): symbol; + + /** + * Returns a key from the global symbol registry matching the given Symbol if found. + * Otherwise, returns a undefined. + * @param sym Symbol to find the key for. + */ + keyFor(sym: symbol): string | undefined; +} + +declare var Symbol: SymbolConstructor; + +/// + +interface SymbolConstructor { + /** + * A method that determines if a constructor object recognizes an object as one of the + * constructor’s instances. Called by the semantics of the instanceof operator. + */ + readonly hasInstance: symbol; + + /** + * A Boolean value that if true indicates that an object should flatten to its array elements + * by Array.prototype.concat. + */ + readonly isConcatSpreadable: symbol; + + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.match method. + */ + readonly match: symbol; + + /** + * A regular expression method that replaces matched substrings of a string. Called by the + * String.prototype.replace method. + */ + readonly replace: symbol; + + /** + * A regular expression method that returns the index within a string that matches the + * regular expression. Called by the String.prototype.search method. + */ + readonly search: symbol; + + /** + * A function valued property that is the constructor function that is used to create + * derived objects. + */ + readonly species: symbol; + + /** + * A regular expression method that splits a string at the indices that match the regular + * expression. Called by the String.prototype.split method. + */ + readonly split: symbol; + + /** + * A method that converts an object to a corresponding primitive value. + * Called by the ToPrimitive abstract operation. + */ + readonly toPrimitive: symbol; + + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + readonly toStringTag: symbol; + + /** + * An Object whose own property names are property names that are excluded from the 'with' + * environment bindings of the associated objects. + */ + readonly unscopables: symbol; +} + +interface Symbol { + readonly [Symbol.toStringTag]: "Symbol"; +} + +interface Array { + /** + * Returns an object whose properties have the value 'true' + * when they will be absent when used in a 'with' statement. + */ + [Symbol.unscopables](): { + copyWithin: boolean; + entries: boolean; + fill: boolean; + find: boolean; + findIndex: boolean; + keys: boolean; + values: boolean; + }; +} + +interface Date { + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "default"): string; + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "string"): string; + /** + * Converts a Date object to a number. + */ + [Symbol.toPrimitive](hint: "number"): number; + /** + * Converts a Date object to a string or number. + * + * @param hint The strings "number", "string", or "default" to specify what primitive to return. + * + * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". + * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". + */ + [Symbol.toPrimitive](hint: string): string | number; +} + +interface Map { + readonly [Symbol.toStringTag]: "Map"; +} + +interface WeakMap{ + readonly [Symbol.toStringTag]: "WeakMap"; +} + +interface Set { + readonly [Symbol.toStringTag]: "Set"; +} + +interface WeakSet { + readonly [Symbol.toStringTag]: "WeakSet"; +} + +interface JSON { + readonly [Symbol.toStringTag]: "JSON"; +} + +interface Function { + /** + * Determines whether the given value inherits from this function if this function was used + * as a constructor function. + * + * A constructor function can control which objects are recognized as its instances by + * 'instanceof' by overriding this method. + */ + [Symbol.hasInstance](value: any): boolean; +} + +interface GeneratorFunction { + readonly [Symbol.toStringTag]: "GeneratorFunction"; +} + +interface Math { + readonly [Symbol.toStringTag]: "Math"; +} + +interface Promise { + readonly [Symbol.toStringTag]: "Promise"; +} + +interface PromiseConstructor { + readonly [Symbol.species]: Function; +} + +interface RegExp { + /** + * Matches a string with this regular expression, and returns an array containing the results of + * that search. + * @param string A string to search within. + */ + [Symbol.match](string: string): RegExpMatchArray | null; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replaceValue A String object or string literal containing the text to replace for every + * successful match of this regular expression. + */ + [Symbol.replace](string: string, replaceValue: string): string; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replacer A function that returns the replacement text. + */ + [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the position beginning first substring match in a regular expression search + * using this regular expression. + * + * @param string The string to search within. + */ + [Symbol.search](string: string): number; + + /** + * Returns an array of substrings that were delimited by strings in the original input that + * match against this regular expression. + * + * If the regular expression contains capturing parentheses, then each time this + * regular expression matches, the results (including any undefined results) of the + * capturing parentheses are spliced. + * + * @param string string value to split + * @param limit if not undefined, the output array is truncated so that it contains no more + * than 'limit' elements. + */ + [Symbol.split](string: string, limit?: number): string[]; +} + +interface RegExpConstructor { + [Symbol.species](): RegExpConstructor; +} + +interface String { + /** + * Matches a string an object that supports being matched against, and returns an array containing the results of that search. + * @param matcher An object that supports being matched against. + */ + match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param searcher An object which supports searching within a string. + */ + search(searcher: { [Symbol.search](string: string): number; }): number; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param splitter An object that can split a string. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + readonly [Symbol.toStringTag]: "ArrayBuffer"; +} + +interface DataView { + readonly [Symbol.toStringTag]: "DataView"; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + readonly [Symbol.toStringTag]: "Int8Array"; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + readonly [Symbol.toStringTag]: "UInt8Array"; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + readonly [Symbol.toStringTag]: "Uint8ClampedArray"; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + readonly [Symbol.toStringTag]: "Int16Array"; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + readonly [Symbol.toStringTag]: "Uint16Array"; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + readonly [Symbol.toStringTag]: "Int32Array"; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + readonly [Symbol.toStringTag]: "Uint32Array"; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + readonly [Symbol.toStringTag]: "Float32Array"; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + readonly [Symbol.toStringTag]: "Float64Array"; +} + ///////////////////////////// diff --git a/lib/lib.es2017.sharedmemory.d.ts b/lib/lib.es2017.sharedmemory.d.ts index c0254f1dc2c..50a38686a90 100644 --- a/lib/lib.es2017.sharedmemory.d.ts +++ b/lib/lib.es2017.sharedmemory.d.ts @@ -43,5 +43,96 @@ interface SharedArrayBufferConstructor { readonly prototype: SharedArrayBuffer; new (byteLength: number): SharedArrayBuffer; } +declare var SharedArrayBuffer: SharedArrayBufferConstructor; -declare var SharedArrayBuffer: SharedArrayBufferConstructor; \ No newline at end of file +interface ArrayBufferTypes { + SharedArrayBuffer: SharedArrayBuffer; +} + +interface Atomics { + /** + * Adds a value to the value at the given position in the array, returning the original value. + * Until this atomic operation completes, any other read or write operation against the array + * will block. + */ + add(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Stores the bitwise AND of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or + * write operation against the array will block. + */ + and(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Replaces the value at the given position in the array if the original value equals the given + * expected value, returning the original value. Until this atomic operation completes, any + * other read or write operation against the array will block. + */ + compareExchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, expectedValue: number, replacementValue: number): number; + + /** + * Replaces the value at the given position in the array, returning the original value. Until + * this atomic operation completes, any other read or write operation against the array will + * block. + */ + exchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Returns a value indicating whether high-performance algorithms can use atomic operations + * (`true`) or must use locks (`false`) for the given number of bytes-per-element of a typed + * array. + */ + isLockFree(size: number): boolean; + + /** + * Returns the value at the given position in the array. Until this atomic operation completes, + * any other read or write operation against the array will block. + */ + load(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number): number; + + /** + * Stores the bitwise OR of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or write + * operation against the array will block. + */ + or(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Stores a value at the given position in the array, returning the new value. Until this + * atomic operation completes, any other read or write operation against the array will block. + */ + store(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Subtracts a value from the value at the given position in the array, returning the original + * value. Until this atomic operation completes, any other read or write operation against the + * array will block. + */ + sub(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * If the value at the given position in the array is equal to the provided value, the current + * agent is put to sleep causing execution to suspend until the timeout expires (returning + * `"timed-out"`) or until the agent is awoken (returning `"ok"`); otherwise, returns + * `"not-equal"`. + */ + wait(typedArray: Int32Array, index: number, value: number, timeout?: number): "ok" | "not-equal" | "timed-out"; + + /** + * Wakes up sleeping agents that are waiting on the given index of the array, returning the + * number of agents that were awoken. + */ + wake(typedArray: Int32Array, index: number, count: number): number; + + /** + * Stores the bitwise XOR of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or write + * operation against the array will block. + */ + xor(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + readonly [Symbol.toStringTag]: "Atomics"; +} + +declare var Atomics: Atomics; \ No newline at end of file diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 1d19198d1d1..f359e519ab1 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1406,6 +1406,14 @@ interface ArrayBuffer { slice(begin: number, end?: number): ArrayBuffer; } +/** + * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. + */ +interface ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} +type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; + interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; @@ -1417,7 +1425,7 @@ interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1559,7 +1567,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; + new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1576,7 +1584,7 @@ interface Int8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1819,7 +1827,7 @@ interface Int8ArrayConstructor { readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1860,7 +1868,7 @@ interface Uint8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2104,7 +2112,7 @@ interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2145,7 +2153,7 @@ interface Uint8ClampedArray { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2389,7 +2397,7 @@ interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2429,7 +2437,7 @@ interface Int16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2673,7 +2681,7 @@ interface Int16ArrayConstructor { readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2714,7 +2722,7 @@ interface Uint16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2958,7 +2966,7 @@ interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2998,7 +3006,7 @@ interface Int32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3242,7 +3250,7 @@ interface Int32ArrayConstructor { readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3282,7 +3290,7 @@ interface Uint32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3526,7 +3534,7 @@ interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3566,7 +3574,7 @@ interface Float32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3810,7 +3818,7 @@ interface Float32ArrayConstructor { readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3851,7 +3859,7 @@ interface Float64Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -4095,7 +4103,7 @@ interface Float64ArrayConstructor { readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 76dc84306ed..4d2428a59ba 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -1406,6 +1406,14 @@ interface ArrayBuffer { slice(begin: number, end?: number): ArrayBuffer; } +/** + * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. + */ +interface ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} +type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; + interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; @@ -1417,7 +1425,7 @@ interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1559,7 +1567,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; + new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1576,7 +1584,7 @@ interface Int8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1819,7 +1827,7 @@ interface Int8ArrayConstructor { readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1860,7 +1868,7 @@ interface Uint8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2104,7 +2112,7 @@ interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2145,7 +2153,7 @@ interface Uint8ClampedArray { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2389,7 +2397,7 @@ interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2429,7 +2437,7 @@ interface Int16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2673,7 +2681,7 @@ interface Int16ArrayConstructor { readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2714,7 +2722,7 @@ interface Uint16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2958,7 +2966,7 @@ interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2998,7 +3006,7 @@ interface Int32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3242,7 +3250,7 @@ interface Int32ArrayConstructor { readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3282,7 +3290,7 @@ interface Uint32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3526,7 +3534,7 @@ interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3566,7 +3574,7 @@ interface Float32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3810,7 +3818,7 @@ interface Float32ArrayConstructor { readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3851,7 +3859,7 @@ interface Float64Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -4095,7 +4103,7 @@ interface Float64ArrayConstructor { readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. @@ -4977,17 +4985,17 @@ interface Array { [Symbol.iterator](): IterableIterator; /** - * Returns an array of key, value pairs for every entry in the array + * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** - * Returns an list of keys in the array + * Returns an iterable of keys in the array */ keys(): IterableIterator; /** - * Returns an list of values in the array + * Returns an iterable of values in the array */ values(): IterableIterator; } @@ -5011,21 +5019,21 @@ interface ArrayConstructor { } interface ReadonlyArray { - /** Iterator */ + /** Iterator of values in the array. */ [Symbol.iterator](): IterableIterator; /** - * Returns an array of key, value pairs for every entry in the array + * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** - * Returns an list of keys in the array + * Returns an iterable of keys in the array */ keys(): IterableIterator; /** - * Returns an list of values in the array + * Returns an iterable of values in the array */ values(): IterableIterator; } @@ -5036,9 +5044,42 @@ interface IArguments { } interface Map { + /** Returns an iterable of entries in the map. */ [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface ReadonlyMap { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ values(): IterableIterator; } @@ -5053,9 +5094,40 @@ interface WeakMapConstructor { } interface Set { + /** Iterates over values in the set. */ [Symbol.iterator](): IterableIterator; + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ entries(): IterableIterator<[T, T]>; + /** + * Despite its name, returns an iterable of the values in the set, + */ keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface ReadonlySet { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ values(): IterableIterator; } @@ -5637,7 +5709,7 @@ interface ProxyHandler { setPrototypeOf? (target: T, v: any): boolean; isExtensible? (target: T): boolean; preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; has? (target: T, p: PropertyKey): boolean; get? (target: T, p: PropertyKey, receiver: any): any; set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; diff --git a/lib/lib.esnext.full.d.ts b/lib/lib.esnext.full.d.ts index d285df3f4db..70db6a78452 100644 --- a/lib/lib.esnext.full.d.ts +++ b/lib/lib.esnext.full.d.ts @@ -22,6 +22,1830 @@ and limitations under the License. /// +declare type PropertyKey = string | number | symbol; + +interface Array { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (this: void, value: T, index: number, obj: Array) => boolean): T | undefined; + find(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): T | undefined; + find(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean): number; + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; + findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): this; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U): Array; + from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; + from(arrayLike: ArrayLike, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; + + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +interface DateConstructor { + new (value: Date): Date; +} + +interface Function { + /** + * Returns the name of the function. Function names are read-only and can not be changed. + */ + readonly name: string; +} + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or −0, the result is +0. + */ + hypot(...values: number[] ): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; +} + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍−‍16. + */ + readonly EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + readonly MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n − 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). + */ + readonly MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface Object { + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source The source object from which to copy properties. + */ + assign(target: T, source: U): T & U; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V): T & U & V; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + * @param source3 The third source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ + assign(target: object, ...sources: any[]): any; + + /** + * Returns an array of all symbol properties found directly on object o. + * @param o Object to retrieve the symbols from. + */ + getOwnPropertySymbols(o: any): symbol[]; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + */ + setPrototypeOf(o: any, proto: object | null): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not + * inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript + * object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor + * property. + */ + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; +} + +interface ReadonlyArray { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean): T | undefined; + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: undefined): T | undefined; + find(predicate: (this: Z, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: Z): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean): number; + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; + findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; +} + +interface RegExp { + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + readonly flags: string; + + /** + * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular + * expression. Default is false. Read-only. + */ + readonly sticky: boolean; + + /** + * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular + * expression. Default is false. Read-only. + */ + readonly unicode: boolean; +} + +interface RegExpConstructor { + new (pattern: RegExp, flags?: string): RegExp; + (pattern: RegExp, flags?: string): RegExp; +} + +interface String { + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number | undefined; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form?: string): string; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; + + /** + * Returns an HTML anchor element and sets the name attribute to the text value + * @param name + */ + anchor(name: string): string; + + /** Returns a HTML element */ + big(): string; + + /** Returns a HTML element */ + blink(): string; + + /** Returns a HTML element */ + bold(): string; + + /** Returns a HTML element */ + fixed(): string; + + /** Returns a HTML element and sets the color attribute value */ + fontcolor(color: string): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: number): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: string): string; + + /** Returns an HTML element */ + italics(): string; + + /** Returns an HTML element and sets the href attribute value */ + link(url: string): string; + + /** Returns a HTML element */ + small(): string; + + /** Returns a HTML element */ + strike(): string; + + /** Returns a HTML element */ + sub(): string; + + /** Returns a HTML element */ + sup(): string; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; + readonly size: number; +} + +interface MapConstructor { + new (): Map; + new (entries?: [K, V][]): Map; + readonly prototype: Map; +} +declare var Map: MapConstructor; + +interface ReadonlyMap { + forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + readonly size: number; +} + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (entries?: [K, V][]): WeakMap; + readonly prototype: WeakMap; +} +declare var WeakMap: WeakMapConstructor; + +interface Set { + add(value: T): this; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface SetConstructor { + new (): Set; + new (values?: T[]): Set; + readonly prototype: Set; +} +declare var Set: SetConstructor; + +interface ReadonlySet { + forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface WeakSet { + add(value: T): this; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (values?: T[]): WeakSet; + readonly prototype: WeakSet; +} +declare var WeakSet: WeakSetConstructor; + + +interface Generator extends Iterator { } + +interface GeneratorFunction { + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + new (...args: any[]): Generator; + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + (...args: any[]): Generator; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: Generator; +} + +interface GeneratorFunctionConstructor { + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): GeneratorFunction; + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + (...args: string[]): GeneratorFunction; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: GeneratorFunction; +} +declare var GeneratorFunction: GeneratorFunctionConstructor; + + +/// + +interface SymbolConstructor { + /** + * A method that returns the default iterator for an object. Called by the semantics of the + * for-of statement. + */ + readonly iterator: symbol; +} + +interface IteratorResult { + done: boolean; + value: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +interface IterableIterator extends Iterator { + [Symbol.iterator](): IterableIterator; +} + +interface Array { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface ArrayConstructor { + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U): Array; + from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; + from(iterable: Iterable, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): Array; +} + +interface ReadonlyArray { + /** Iterator of values in the array. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface Map { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface ReadonlyMap { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface MapConstructor { + new (iterable: Iterable<[K, V]>): Map; +} + +interface WeakMap { } + +interface WeakMapConstructor { + new (iterable: Iterable<[K, V]>): WeakMap; +} + +interface Set { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface ReadonlySet { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface SetConstructor { + new (iterable: Iterable): Set; +} + +interface WeakSet { } + +interface WeakSetConstructor { + new (iterable: Iterable): WeakSet; +} + +interface Promise { } + +interface PromiseConstructor { + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: Iterable>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: Iterable>): Promise; +} + +declare namespace Reflect { + function enumerate(target: object): IterableIterator; +} + +interface String { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int8ArrayConstructor { + new (elements: Iterable): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int8Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; + + from(arrayLike: Iterable): Int8Array; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ArrayConstructor { + new (elements: Iterable): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; + + from(arrayLike: Iterable): Uint8Array; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ClampedArrayConstructor { + new (elements: Iterable): Uint8ClampedArray; + + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; + + from(arrayLike: Iterable): Uint8ClampedArray; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int16ArrayConstructor { + new (elements: Iterable): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int16Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; + + from(arrayLike: Iterable): Int16Array; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint16ArrayConstructor { + new (elements: Iterable): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint16Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; + + from(arrayLike: Iterable): Uint16Array; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int32ArrayConstructor { + new (elements: Iterable): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; + + from(arrayLike: Iterable): Int32Array; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint32ArrayConstructor { + new (elements: Iterable): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; + + from(arrayLike: Iterable): Uint32Array; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float32ArrayConstructor { + new (elements: Iterable): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; + + from(arrayLike: Iterable): Float32Array; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float64ArrayConstructor { + new (elements: Iterable): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float64Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; + + from(arrayLike: Iterable): Float64Array; +} + + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Promise; + + /** + * Creates a new Promise. + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: (T | PromiseLike)[]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: (T | PromiseLike)[]): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; +} + +declare var Promise: PromiseConstructor; + +interface ProxyHandler { + getPrototypeOf? (target: T): object | null; + setPrototypeOf? (target: T, v: any): boolean; + isExtensible? (target: T): boolean; + preventExtensions? (target: T): boolean; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; + has? (target: T, p: PropertyKey): boolean; + get? (target: T, p: PropertyKey, receiver: any): any; + set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; + deleteProperty? (target: T, p: PropertyKey): boolean; + defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; + enumerate? (target: T): PropertyKey[]; + ownKeys? (target: T): PropertyKey[]; + apply? (target: T, thisArg: any, argArray?: any): any; + construct? (target: T, argArray: any, newTarget?: any): object; +} + +interface ProxyConstructor { + revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; + new (target: T, handler: ProxyHandler): T; +} +declare var Proxy: ProxyConstructor; + + +declare namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; + function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: object, propertyKey: PropertyKey): boolean; + function get(target: object, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: object): object; + function has(target: object, propertyKey: PropertyKey): boolean; + function isExtensible(target: object): boolean; + function ownKeys(target: object): Array; + function preventExtensions(target: object): boolean; + function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: object, proto: any): boolean; +} + + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): symbol; +} + +interface SymbolConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Symbol; + + /** + * Returns a new unique Symbol value. + * @param description Description of the new Symbol object. + */ + (description?: string | number): symbol; + + /** + * Returns a Symbol object from the global symbol registry matching the given key if found. + * Otherwise, returns a new symbol with this key. + * @param key key to search for. + */ + for(key: string): symbol; + + /** + * Returns a key from the global symbol registry matching the given Symbol if found. + * Otherwise, returns a undefined. + * @param sym Symbol to find the key for. + */ + keyFor(sym: symbol): string | undefined; +} + +declare var Symbol: SymbolConstructor; + +/// + +interface SymbolConstructor { + /** + * A method that determines if a constructor object recognizes an object as one of the + * constructor’s instances. Called by the semantics of the instanceof operator. + */ + readonly hasInstance: symbol; + + /** + * A Boolean value that if true indicates that an object should flatten to its array elements + * by Array.prototype.concat. + */ + readonly isConcatSpreadable: symbol; + + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.match method. + */ + readonly match: symbol; + + /** + * A regular expression method that replaces matched substrings of a string. Called by the + * String.prototype.replace method. + */ + readonly replace: symbol; + + /** + * A regular expression method that returns the index within a string that matches the + * regular expression. Called by the String.prototype.search method. + */ + readonly search: symbol; + + /** + * A function valued property that is the constructor function that is used to create + * derived objects. + */ + readonly species: symbol; + + /** + * A regular expression method that splits a string at the indices that match the regular + * expression. Called by the String.prototype.split method. + */ + readonly split: symbol; + + /** + * A method that converts an object to a corresponding primitive value. + * Called by the ToPrimitive abstract operation. + */ + readonly toPrimitive: symbol; + + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + readonly toStringTag: symbol; + + /** + * An Object whose own property names are property names that are excluded from the 'with' + * environment bindings of the associated objects. + */ + readonly unscopables: symbol; +} + +interface Symbol { + readonly [Symbol.toStringTag]: "Symbol"; +} + +interface Array { + /** + * Returns an object whose properties have the value 'true' + * when they will be absent when used in a 'with' statement. + */ + [Symbol.unscopables](): { + copyWithin: boolean; + entries: boolean; + fill: boolean; + find: boolean; + findIndex: boolean; + keys: boolean; + values: boolean; + }; +} + +interface Date { + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "default"): string; + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "string"): string; + /** + * Converts a Date object to a number. + */ + [Symbol.toPrimitive](hint: "number"): number; + /** + * Converts a Date object to a string or number. + * + * @param hint The strings "number", "string", or "default" to specify what primitive to return. + * + * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". + * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". + */ + [Symbol.toPrimitive](hint: string): string | number; +} + +interface Map { + readonly [Symbol.toStringTag]: "Map"; +} + +interface WeakMap{ + readonly [Symbol.toStringTag]: "WeakMap"; +} + +interface Set { + readonly [Symbol.toStringTag]: "Set"; +} + +interface WeakSet { + readonly [Symbol.toStringTag]: "WeakSet"; +} + +interface JSON { + readonly [Symbol.toStringTag]: "JSON"; +} + +interface Function { + /** + * Determines whether the given value inherits from this function if this function was used + * as a constructor function. + * + * A constructor function can control which objects are recognized as its instances by + * 'instanceof' by overriding this method. + */ + [Symbol.hasInstance](value: any): boolean; +} + +interface GeneratorFunction { + readonly [Symbol.toStringTag]: "GeneratorFunction"; +} + +interface Math { + readonly [Symbol.toStringTag]: "Math"; +} + +interface Promise { + readonly [Symbol.toStringTag]: "Promise"; +} + +interface PromiseConstructor { + readonly [Symbol.species]: Function; +} + +interface RegExp { + /** + * Matches a string with this regular expression, and returns an array containing the results of + * that search. + * @param string A string to search within. + */ + [Symbol.match](string: string): RegExpMatchArray | null; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replaceValue A String object or string literal containing the text to replace for every + * successful match of this regular expression. + */ + [Symbol.replace](string: string, replaceValue: string): string; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replacer A function that returns the replacement text. + */ + [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the position beginning first substring match in a regular expression search + * using this regular expression. + * + * @param string The string to search within. + */ + [Symbol.search](string: string): number; + + /** + * Returns an array of substrings that were delimited by strings in the original input that + * match against this regular expression. + * + * If the regular expression contains capturing parentheses, then each time this + * regular expression matches, the results (including any undefined results) of the + * capturing parentheses are spliced. + * + * @param string string value to split + * @param limit if not undefined, the output array is truncated so that it contains no more + * than 'limit' elements. + */ + [Symbol.split](string: string, limit?: number): string[]; +} + +interface RegExpConstructor { + [Symbol.species](): RegExpConstructor; +} + +interface String { + /** + * Matches a string an object that supports being matched against, and returns an array containing the results of that search. + * @param matcher An object that supports being matched against. + */ + match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param searcher An object which supports searching within a string. + */ + search(searcher: { [Symbol.search](string: string): number; }): number; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param splitter An object that can split a string. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + readonly [Symbol.toStringTag]: "ArrayBuffer"; +} + +interface DataView { + readonly [Symbol.toStringTag]: "DataView"; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + readonly [Symbol.toStringTag]: "Int8Array"; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + readonly [Symbol.toStringTag]: "UInt8Array"; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + readonly [Symbol.toStringTag]: "Uint8ClampedArray"; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + readonly [Symbol.toStringTag]: "Int16Array"; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + readonly [Symbol.toStringTag]: "Uint16Array"; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + readonly [Symbol.toStringTag]: "Int32Array"; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + readonly [Symbol.toStringTag]: "Uint32Array"; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + readonly [Symbol.toStringTag]: "Float32Array"; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + readonly [Symbol.toStringTag]: "Float64Array"; +} + + ///////////////////////////// /// IE DOM APIs diff --git a/lib/tsc.js b/lib/tsc.js index 693a32dc98b..4c846c034f8 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -15,12 +15,449 @@ and limitations under the License. var ts; (function (ts) { + var SyntaxKind; + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; + SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; + SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; + SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; + SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 126] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 127] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 128] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 129] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 130] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 131] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 132] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 133] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 134] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 135] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 136] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 137] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 138] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 139] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 140] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 141] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 142] = "OfKeyword"; + SyntaxKind[SyntaxKind["QualifiedName"] = 143] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 144] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["TypeParameter"] = 145] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 146] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 147] = "Decorator"; + SyntaxKind[SyntaxKind["PropertySignature"] = 148] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 149] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 150] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 151] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 152] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 153] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 154] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 155] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 156] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 157] = "IndexSignature"; + SyntaxKind[SyntaxKind["TypePredicate"] = 158] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 159] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 160] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 161] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 162] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 163] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 164] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 165] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 166] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 167] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 168] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 169] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 170] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 171] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 172] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 173] = "LiteralType"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 174] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 175] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 176] = "BindingElement"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 177] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 178] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 179] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 180] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 181] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 182] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 183] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 184] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 185] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 186] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 187] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 188] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 189] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 190] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 191] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 192] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 193] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 194] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 195] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 196] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 197] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 198] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 199] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 200] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 201] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 202] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 203] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 204] = "MetaProperty"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 205] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 206] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["Block"] = 207] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 208] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 209] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 210] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 211] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 212] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 213] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 214] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 215] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 216] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 217] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 218] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 219] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 220] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 221] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 222] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 223] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 224] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 225] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 226] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 227] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 228] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 229] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 230] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 231] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 232] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 233] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 234] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 235] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 236] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 237] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 238] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 239] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 240] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 241] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 242] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 243] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 244] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 245] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 246] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 247] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 248] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["JsxElement"] = 249] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 250] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 251] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 252] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 253] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 254] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 255] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 256] = "JsxExpression"; + SyntaxKind[SyntaxKind["CaseClause"] = 257] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 258] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 259] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 260] = "CatchClause"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 261] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 262] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 263] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["EnumMember"] = 264] = "EnumMember"; + SyntaxKind[SyntaxKind["SourceFile"] = 265] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 266] = "Bundle"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 267] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 268] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 269] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 270] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 271] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 272] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 273] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 274] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 275] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 276] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 277] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 278] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 279] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 280] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 281] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 282] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 284] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 285] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 286] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 287] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 288] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 289] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 290] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 291] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocLiteralType"] = 293] = "JSDocLiteralType"; + SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; + SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 142] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 158] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 173] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = 142] = "LastToken"; + SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; + SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; + SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 143] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 267] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 283] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode"; + })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); + var NodeFlags; + (function (NodeFlags) { + NodeFlags[NodeFlags["None"] = 0] = "None"; + NodeFlags[NodeFlags["Let"] = 1] = "Let"; + NodeFlags[NodeFlags["Const"] = 2] = "Const"; + NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; + NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; + NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; + NodeFlags[NodeFlags["ContextFlags"] = 96256] = "ContextFlags"; + NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; + })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); + var ModifierFlags; + (function (ModifierFlags) { + ModifierFlags[ModifierFlags["None"] = 0] = "None"; + ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; + ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; + ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; + ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; + ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; + ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; + ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; + ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; + ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; + ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; + ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; + ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); + var JsxFlags; + (function (JsxFlags) { + JsxFlags[JsxFlags["None"] = 0] = "None"; + JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; + JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; + })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); + var RelationComparisonResult; + (function (RelationComparisonResult) { + RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; + RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; + RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; + })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); + var GeneratedIdentifierKind; + (function (GeneratedIdentifierKind) { + GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; + })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var NumericLiteralFlags; + (function (NumericLiteralFlags) { + NumericLiteralFlags[NumericLiteralFlags["None"] = 0] = "None"; + NumericLiteralFlags[NumericLiteralFlags["Scientific"] = 2] = "Scientific"; + NumericLiteralFlags[NumericLiteralFlags["Octal"] = 4] = "Octal"; + NumericLiteralFlags[NumericLiteralFlags["HexSpecifier"] = 8] = "HexSpecifier"; + NumericLiteralFlags[NumericLiteralFlags["BinarySpecifier"] = 16] = "BinarySpecifier"; + NumericLiteralFlags[NumericLiteralFlags["OctalSpecifier"] = 32] = "OctalSpecifier"; + NumericLiteralFlags[NumericLiteralFlags["BinaryOrOctalSpecifier"] = 48] = "BinaryOrOctalSpecifier"; + })(NumericLiteralFlags = ts.NumericLiteralFlags || (ts.NumericLiteralFlags = {})); + var FlowFlags; + (function (FlowFlags) { + FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; + FlowFlags[FlowFlags["Start"] = 2] = "Start"; + FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel"; + FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel"; + FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; + FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; + FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; + FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; + FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; + FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; + FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; + FlowFlags[FlowFlags["Label"] = 12] = "Label"; + FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; + })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); var OperationCanceledException = (function () { function OperationCanceledException() { } return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -30,13 +467,60 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + var TypeFormatFlags; + (function (TypeFormatFlags) { + TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 2] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 4] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 8] = "WriteArrowStyleSignature"; + TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 16] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 64] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 2048] = "SuppressAnyReturnType"; + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 4096] = "AddUndefined"; + })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var SymbolFormatFlags; + (function (SymbolFormatFlags) { + SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; + SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; + SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); + var SymbolAccessibility; + (function (SymbolAccessibility) { + SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; + SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; + SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; + })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + var SyntheticSymbolKind; + (function (SyntheticSymbolKind) { + SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; + SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; + })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); + var TypePredicateKind; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; @@ -51,6 +535,196 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var SymbolFlags; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; + SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; + SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags[SymbolFlags["ExportType"] = 2097152] = "ExportType"; + SymbolFlags[SymbolFlags["ExportNamespace"] = 4194304] = "ExportNamespace"; + SymbolFlags[SymbolFlags["Alias"] = 8388608] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 16777216] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 33554432] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 67108864] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 134217728] = "Transient"; + SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; + SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; + SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; + SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; + SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 107454] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 899519] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792968] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 106639] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["AliasExcludes"] = 8388608] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 8914931] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; + SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["Export"] = 7340032] = "Export"; + SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; + SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; + })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + var CheckFlags; + (function (CheckFlags) { + CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; + CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; + CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod"; + CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; + CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; + CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; + CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; + CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + var NodeCheckFlags; + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; + NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; + NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var TypeFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 1] = "Any"; + TypeFlags[TypeFlags["String"] = 2] = "String"; + TypeFlags[TypeFlags["Number"] = 4] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; + TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; + TypeFlags[TypeFlags["Void"] = 1024] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 4096] = "Null"; + TypeFlags[TypeFlags["Never"] = 8192] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 32768] = "Object"; + TypeFlags[TypeFlags["Union"] = 65536] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 131072] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 262144] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 524288] = "IndexedAccess"; + TypeFlags[TypeFlags["FreshLiteral"] = 1048576] = "FreshLiteral"; + TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; + TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; + TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; + TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; + TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; + TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; + TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; + TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; + TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; + TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; + })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + var ObjectFlags; + (function (ObjectFlags) { + ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; + ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; + ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; + ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; + ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; + ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; + ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; + ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; + ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; + ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + var SignatureKind; + (function (SignatureKind) { + SignatureKind[SignatureKind["Call"] = 0] = "Call"; + SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; + })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + var IndexKind; + (function (IndexKind) { + IndexKind[IndexKind["String"] = 0] = "String"; + IndexKind[IndexKind["Number"] = 1] = "Number"; + })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + var SpecialPropertyAssignmentKind; + (function (SpecialPropertyAssignmentKind) { + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -71,6 +745,179 @@ var ts; ModuleKind[ModuleKind["System"] = 4] = "System"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit[JsxEmit["None"] = 0] = "None"; + JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; + JsxEmit[JsxEmit["React"] = 2] = "React"; + JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; + })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); + var ScriptKind; + (function (ScriptKind) { + ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; + ScriptKind[ScriptKind["JS"] = 1] = "JS"; + ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; + ScriptKind[ScriptKind["TS"] = 3] = "TS"; + ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; + ScriptKind[ScriptKind["External"] = 5] = "External"; + })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; + ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; + ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; + ScriptTarget[ScriptTarget["ESNext"] = 5] = "ESNext"; + ScriptTarget[ScriptTarget["Latest"] = 5] = "Latest"; + })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); + var LanguageVariant; + (function (LanguageVariant) { + LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; + LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; + })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); + var DiagnosticStyle; + (function (DiagnosticStyle) { + DiagnosticStyle[DiagnosticStyle["Simple"] = 0] = "Simple"; + DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; + })(DiagnosticStyle = ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); + var WatchDirectoryFlags; + (function (WatchDirectoryFlags) { + WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; + WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; + })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + var CharacterCodes; + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; + CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; + CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; + CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); var Extension; (function (Extension) { Extension[Extension["Ts"] = 0] = "Ts"; @@ -80,6 +927,126 @@ var ts; Extension[Extension["Jsx"] = 4] = "Jsx"; Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; })(Extension = ts.Extension || (ts.Extension = {})); + var TransformFlags; + (function (TransformFlags) { + TransformFlags[TransformFlags["None"] = 0] = "None"; + TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; + TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; + TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; + TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; + TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; + TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; + TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 540087617] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + var EmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; + EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; + EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; + EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; + EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; + EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); + var ExternalEmitHelpers; + (function (ExternalEmitHelpers) { + ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; + ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; + ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; + ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; + ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; + ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; + ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; + ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; + ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; + ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; + ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; + })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); + var EmitHint; + (function (EmitHint) { + EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; + EmitHint[EmitHint["Expression"] = 1] = "Expression"; + EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; + EmitHint[EmitHint["Unspecified"] = 3] = "Unspecified"; + })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -145,6 +1112,12 @@ var ts; ts.version = "2.4.0"; })(ts || (ts = {})); (function (ts) { + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; function createDictionaryObject() { @@ -278,6 +1251,12 @@ var ts; return getCanonicalFileName(nonCanonicalizedPath); } ts.toPath = toPath; + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); function length(array) { return array ? array.length : 0; } @@ -315,6 +1294,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; function every(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -519,6 +1507,28 @@ var ts; return result; } ts.flatMap = flatMap; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1543,6 +2553,10 @@ var ts; return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -1811,6 +2825,13 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + var ExtensionPriority; + (function (ExtensionPriority) { + ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; + ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; + ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; + ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; + })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { @@ -1895,6 +2916,13 @@ var ts; getTypeConstructor: function () { return Type; }, getSignatureConstructor: function () { return Signature; } }; + var AssertionLevel; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); var Debug; (function (Debug) { Debug.currentAssertionLevel = 0; @@ -2214,6 +3242,11 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); function fileSystemEntryExists(path, entryKind) { try { var stat = _fs.statSync(path); @@ -2579,6 +3612,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -2686,7 +3720,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -2881,6 +3915,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3176,6 +4218,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -3221,6 +4264,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -3302,6 +4347,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -3850,9 +4898,10 @@ var ts; } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -4982,9 +6031,7 @@ var ts; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -5141,26 +6188,28 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; } @@ -5367,10 +6416,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 && isConst(node); } @@ -5622,6 +6667,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160: + case 161: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151: @@ -5846,6 +6900,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 || node.kind === 182; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183) { return node.tag; @@ -6318,6 +7376,12 @@ var ts; return node && node.dotDotDotToken !== undefined; } ts.isDeclaredRestParam = isDeclaredRestParam; + var AssignmentKind; + (function (AssignmentKind) { + AssignmentKind[AssignmentKind["None"] = 0] = "None"; + AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite"; + AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound"; + })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {})); function getAssignmentTargetKind(node) { var parent = node.parent; while (true) { @@ -6393,21 +7457,46 @@ var ts; } ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { - if (name.kind !== 71 && name.kind !== 9 && name.kind !== 8) { - return false; + switch (name.kind) { + case 71: + case 9: + case 8: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 || parent.kind === 246) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0: + case 2: + return undefined; + case 1: + if (lhs.kind === 71) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4: + case 5: + return lhs.name; + case 3: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 144 && @@ -6507,21 +7596,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -6544,7 +7631,18 @@ var ts; return 2 <= token && token <= 7; } ts.isTrivia = isTrivia; + var FunctionFlags; + (function (FunctionFlags) { + FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; + FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; + FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; + FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; + })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4; + } var flags = 0; switch (node.kind) { case 228: @@ -6589,7 +7687,8 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -6698,6 +7797,11 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; + var Associativity; + (function (Associativity) { + Associativity[Associativity["Left"] = 0] = "Left"; + Associativity[Associativity["Right"] = 1] = "Right"; + })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); var hasArguments = expression.kind === 182 && expression.arguments !== undefined; @@ -6859,6 +7963,8 @@ var ts; return 2; case 198: return 1; + case 297: + return 0; default: return -1; } @@ -6962,12 +8068,13 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -7056,7 +8163,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -7108,7 +8215,7 @@ var ts; } ts.getSourceFilesToEmit = getSourceFilesToEmit; function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { @@ -7597,13 +8704,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 1: + return lineFeed; } - else if (options.newLine === 1) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -7851,10 +8958,6 @@ var ts; return node.kind === 71; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { return isIdentifier(node) && node.autoGenerateKind > 0; } @@ -7922,9 +9025,20 @@ var ts; || kind === 153 || kind === 154 || kind === 157 - || kind === 206; + || kind === 206 + || kind === 247; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 + || kind === 155 + || kind === 148 + || kind === 150 + || kind === 157 + || kind === 247; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 @@ -8122,6 +9236,7 @@ var ts; || kind === 198 || kind === 202 || kind === 200 + || kind === 297 || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -8208,6 +9323,10 @@ var ts; return node.kind === 237; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239; } @@ -8230,6 +9349,10 @@ var ts; return node.kind === 246; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 || node.kind === 232; } @@ -8301,8 +9424,8 @@ var ts; || kind === 213 || kind === 220 || kind === 295 - || kind === 298 - || kind === 297; + || kind === 299 + || kind === 298; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -8418,6 +9541,48 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + } + if (getCheckFlags(s) & 6) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 ? 8 : + checkFlags & 64 ? 4 : + 16; + var staticModifier = checkFlags & 512 ? 32 : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216) { + return 4 | 32; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -8756,15 +9921,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; node.autoGenerateKind = 0; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; function createTempVariable(recordTempVariable) { var name = createIdentifier(""); @@ -8852,237 +10026,12 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170); - typeOperatorNode.operator = 127; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -9093,42 +10042,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146); node.decorators = asNodeArray(decorators); @@ -9165,6 +10078,26 @@ var ts; : node; } ts.updateDecorator = updateDecorator; + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149); node.decorators = asNodeArray(decorators); @@ -9186,7 +10119,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -9199,7 +10149,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -9209,7 +10159,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -9277,6 +10227,249 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170); + node.operator = 127; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174); node.elements = createNodeArray(elements); @@ -9322,9 +10515,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -9337,9 +10529,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -9387,9 +10578,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -9579,10 +10770,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -9709,6 +10900,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205); node.expression = expression; @@ -9723,6 +10927,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206); + } + ts.createSemicolonClassElement = createSemicolonClassElement; function createBlock(statements, multiLine) { var block = createSynthesizedNode(207); block.statements = createNodeArray(statements); @@ -9732,7 +10940,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -9752,35 +10960,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209); } @@ -9999,6 +11178,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227); + node.flags |= flags & 3; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228); node.decorators = asNodeArray(decorators); @@ -10047,6 +11259,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232); node.decorators = asNodeArray(decorators); @@ -10067,7 +11321,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233); - node.flags |= flags; + node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -10108,6 +11362,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237); node.decorators = asNodeArray(decorators); @@ -10138,7 +11404,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -10324,19 +11591,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253); node.name = name; @@ -10351,6 +11605,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255); node.expression = expression; @@ -10376,20 +11642,6 @@ var ts; : node; } ts.updateJsxExpression = updateJsxExpression; - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257); node.expression = ts.parenthesizeExpressionForList(expression); @@ -10398,10 +11650,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -10411,12 +11663,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -10425,10 +11689,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer) { @@ -10440,10 +11704,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -10454,10 +11718,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -10467,10 +11731,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; function createEnumMember(name, initializer) { @@ -10565,14 +11828,14 @@ var ts; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(299); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(298); node.emitNode = {}; node.original = original; return node; @@ -10593,6 +11856,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266); node.sourceFiles = sourceFiles; @@ -10903,6 +12189,25 @@ var ts; } })(ts || (ts = {})); (function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -11143,7 +12448,9 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -11250,9 +12557,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -11363,16 +12671,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 185) { @@ -11541,6 +12839,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166: + case 167: + case 160: + case 161: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { var clone_1 = ts.getMutableClone(originalOuterExpression); @@ -11580,6 +12906,13 @@ var ts; return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; + var OuterExpressionKinds; + (function (OuterExpressionKinds) { + OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; + OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions"; + OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; + OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; + })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); function skipOuterExpressions(node, kinds) { if (kinds === void 0) { kinds = 7; } var previousNode; @@ -11686,7 +13019,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -12343,6 +13676,8 @@ var ts; return visitNode(cbNode, node.expression); case 247: return visitNodes(cbNodes, node.decorators); + case 297: + return visitNodes(cbNodes, node.elements); case 249: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -16204,6 +17539,43 @@ var ts; : undefined; }); } + var ParsingContext; + (function (ParsingContext) { + ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; + ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements"; + ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses"; + ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; + ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers"; + ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers"; + ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers"; + ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement"; + ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations"; + ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements"; + ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements"; + ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions"; + ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; + ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes"; + ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; + ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; + ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; + ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["JSDocFunctionParameters"] = 23] = "JSDocFunctionParameters"; + ParsingContext[ParsingContext["JSDocTypeArguments"] = 24] = "JSDocTypeArguments"; + ParsingContext[ParsingContext["JSDocRecordMembers"] = 25] = "JSDocRecordMembers"; + ParsingContext[ParsingContext["JSDocTupleTypes"] = 26] = "JSDocTupleTypes"; + ParsingContext[ParsingContext["Count"] = 27] = "Count"; + })(ParsingContext || (ParsingContext = {})); + var Tristate; + (function (Tristate) { + Tristate[Tristate["False"] = 0] = "False"; + Tristate[Tristate["True"] = 1] = "True"; + Tristate[Tristate["Unknown"] = 2] = "Unknown"; + })(Tristate || (Tristate = {})); var JSDocParser; (function (JSDocParser) { function isJSDocType() { @@ -16500,6 +17872,12 @@ var ts; return comment; } JSDocParser.parseJSDocComment = parseJSDocComment; + var JSDocState; + (function (JSDocState) { + JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; + JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; + JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; + })(JSDocState || (JSDocState = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; start = start || 0; @@ -16642,6 +18020,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -17296,10 +18676,20 @@ var ts; } } } + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); })(ts || (ts = {})); var ts; (function (ts) { + var ModuleInstanceState; + (function (ModuleInstanceState) { + ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; + ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; + ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; + })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); function getModuleInstanceState(node) { if (node.kind === 230 || node.kind === 231) { return 0; @@ -17338,6 +18728,18 @@ var ts; } } ts.getModuleInstanceState = getModuleInstanceState; + var ContainerFlags; + (function (ContainerFlags) { + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer"; + ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike"; + ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; + ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; + ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; + ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; + })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -17380,7 +18782,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -17408,7 +18810,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { return true; } else { @@ -17441,19 +18843,20 @@ var ts; } } function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144) { - var nameExpression = node.name.expression; + if (name.kind === 144) { + var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152: @@ -17549,9 +18952,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -18575,6 +19978,11 @@ var ts; typeLiteralSymbol.members.set(symbol.name, symbol); } function bindObjectLiteralExpression(node) { + var ElementKind; + (function (ElementKind) { + ElementKind[ElementKind["Property"] = 1] = "Property"; + ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; + })(ElementKind || (ElementKind = {})); if (inStrictMode) { var seen = ts.createMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { @@ -19196,7 +20604,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { @@ -19211,7 +20619,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -19226,7 +20634,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -19239,7 +20647,7 @@ var ts; return bindAnonymousDeclaration(node, 16, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -19965,12 +21373,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -20254,6 +21661,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -20387,12 +21796,18 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -20422,7 +21837,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -20741,6 +22155,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -20885,13 +22300,16 @@ var ts; tryFindAmbientModuleWithoutAugmentations: function (moduleName) { return tryFindAmbientModule(moduleName, false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4, "unknown"); @@ -20964,11 +22382,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32, ""); - var zeroType = getLiteralTypeForText(64, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -20982,6 +22402,66 @@ var ts; var potentialNewTargetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); + var TypeFacts; + (function (TypeFacts) { + TypeFacts[TypeFacts["None"] = 0] = "None"; + TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; + TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; + TypeFacts[TypeFacts["TypeofEQBoolean"] = 4] = "TypeofEQBoolean"; + TypeFacts[TypeFacts["TypeofEQSymbol"] = 8] = "TypeofEQSymbol"; + TypeFacts[TypeFacts["TypeofEQObject"] = 16] = "TypeofEQObject"; + TypeFacts[TypeFacts["TypeofEQFunction"] = 32] = "TypeofEQFunction"; + TypeFacts[TypeFacts["TypeofEQHostObject"] = 64] = "TypeofEQHostObject"; + TypeFacts[TypeFacts["TypeofNEString"] = 128] = "TypeofNEString"; + TypeFacts[TypeFacts["TypeofNENumber"] = 256] = "TypeofNENumber"; + TypeFacts[TypeFacts["TypeofNEBoolean"] = 512] = "TypeofNEBoolean"; + TypeFacts[TypeFacts["TypeofNESymbol"] = 1024] = "TypeofNESymbol"; + TypeFacts[TypeFacts["TypeofNEObject"] = 2048] = "TypeofNEObject"; + TypeFacts[TypeFacts["TypeofNEFunction"] = 4096] = "TypeofNEFunction"; + TypeFacts[TypeFacts["TypeofNEHostObject"] = 8192] = "TypeofNEHostObject"; + TypeFacts[TypeFacts["EQUndefined"] = 16384] = "EQUndefined"; + TypeFacts[TypeFacts["EQNull"] = 32768] = "EQNull"; + TypeFacts[TypeFacts["EQUndefinedOrNull"] = 65536] = "EQUndefinedOrNull"; + TypeFacts[TypeFacts["NEUndefined"] = 131072] = "NEUndefined"; + TypeFacts[TypeFacts["NENull"] = 262144] = "NENull"; + TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull"; + TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy"; + TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; + TypeFacts[TypeFacts["Discriminatable"] = 4194304] = "Discriminatable"; + TypeFacts[TypeFacts["All"] = 8388607] = "All"; + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; + TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; + TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts"; + TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts"; + TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts"; + TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts"; + TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts"; + TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts"; + TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts"; + TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts"; + TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts"; + TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 6166480] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 8378320] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 6164448] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 8376288] = "FunctionFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ "string": 1, "number": 2, @@ -21031,6 +22511,19 @@ var ts; var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); var _displayBuilder; + var TypeSystemPropertyName; + (function (TypeSystemPropertyName) { + TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; + TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; + })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); + var CheckMode; + (function (CheckMode) { + CheckMode[CheckMode["Normal"] = 0] = "Normal"; + CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; + CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; + })(CheckMode || (CheckMode = {})); var builtinGlobals = ts.createMap(); builtinGlobals.set(undefinedSymbol.name, undefinedSymbol); initializeTypeChecker(); @@ -21152,16 +22645,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 || source.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -21234,9 +22727,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); } @@ -21244,7 +22734,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -21272,7 +22762,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -21347,7 +22838,11 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; var result; var lastLocation; var propertyWithInvalidInitializer; @@ -21356,7 +22851,7 @@ var ts; var isInExternalModule = false; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { if (meaning & result.flags & 793064 && lastLocation.kind !== 283) { @@ -21403,12 +22898,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931)) { + if (result = lookup(moduleExports, name, meaning & 8914931)) { break loop; } break; case 232: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; @@ -21417,7 +22912,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455)) { + if (lookup(ctor.locals, name, meaning & 107455)) { propertyWithInvalidInitializer = location; } } @@ -21426,7 +22921,7 @@ var ts; case 229: case 199: case 230: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -21448,7 +22943,7 @@ var ts; case 144: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -21495,7 +22990,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -21505,7 +23000,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -21602,6 +23107,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -21633,13 +23142,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -21651,7 +23160,7 @@ var ts; if (node.kind === 237) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -21754,10 +23263,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920, false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); @@ -21773,7 +23282,7 @@ var ts; case 242: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); case 243: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236: @@ -21895,7 +23404,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -21915,6 +23424,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, true); if (ambientModule) { return ambientModule; @@ -21974,7 +23488,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -22115,7 +23628,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } function isReservedMemberName(name) { return name.charCodeAt(0) === 95 && @@ -22385,34 +23898,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3, typeNode, sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -22422,12 +23960,12 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; return undefined; @@ -22444,23 +23982,25 @@ var ts; if (type.flags & 8) { return ts.createKeywordTypeNode(122); } - if (type.flags & 16) { - var name = symbolToName(type.symbol, false); + if (type.flags & 256 && !(type.flags & 65536)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064, false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, undefined); + } + if (type.flags & 272) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } if (type.flags & (32)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); } if (type.flags & (64)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } if (type.flags & 1024) { return ts.createKeywordTypeNode(105); } @@ -22480,8 +24020,8 @@ var ts; return ts.createKeywordTypeNode(134); } if (type.flags & 16384 && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -22492,72 +24032,53 @@ var ts; ts.Debug.assert(!!(type.flags & 32768)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3) { - ts.Debug.assert(!!(type.flags & 32768)); - var name = symbolToName(type.symbol, false); + if (type.flags & 16384 || objectFlags & 3) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } - if (type.flags & 16384) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064, false).accessibility === 0) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166, unionTypeNodes); + if (type.flags & (65536 | 131072)) { + var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 ? 166 : 167, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072) { - return ts.createUnionOrIntersectionTypeNode(167, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 | 32)) { ts.Debug.assert(!!(type.flags & 32768)); return createAnonymousTypeNode(type); } if (type.flags & 262144) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -22565,12 +24086,12 @@ var ts; if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455); } else if (ts.contains(context.symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - var entityName = symbolToName(typeAlias, false); + var entityName = symbolToName(typeAlias, context, 793064, false); return ts.createTypeReferenceNode(entityName, undefined); } else { @@ -22612,41 +24133,52 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -22654,7 +24186,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -22664,48 +24196,72 @@ var ts; i++; } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - var qualifiedNamePart = symbolToName(parent, true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, undefined); + qualifiedName = ts.createQualifiedName(namePart, undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); } var properties = resolvedType.properties; if (!properties) { @@ -22714,74 +24270,121 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455, true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 ? ts.createToken(55) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); - var name = ts.getNameFromIndexInfo(indexInfo); - var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); + var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064, true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24), ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 | 16777216); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0, true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -22789,18 +24392,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -22809,20 +24412,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } function getSymbolChain(symbol, meaning, endOfChain) { @@ -22848,28 +24441,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199: + return "(Anonymous class)"; + case 186: + case 187: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -22887,12 +24481,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144)) { if (t.flags & (128 | 256)) { - var baseType = t.flags & 128 ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -22928,13 +24524,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -22977,7 +24574,7 @@ var ts; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { if (flags & 1) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -23042,12 +24639,15 @@ var ts; else if (getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 23); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 && !(type.flags & 65536)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 || type.flags & (16 | 16384)) { + else if (getObjectFlags(type) & 3 || type.flags & (272 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 512) && type.aliasSymbol && @@ -23384,7 +24984,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -23635,10 +25235,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 8388608); } var result = []; if (exportSymbol) { @@ -23759,7 +25356,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -23859,7 +25456,7 @@ var ts; return expr.kind === 177 && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; + return strictNullChecks && optional ? getNullableType(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536) { @@ -23937,6 +25534,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 ? declaration : @@ -23953,16 +25551,23 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536) { - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { @@ -24172,7 +25777,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 ? includeFalsyTypes(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 67108864 ? getNullableType(type, 2048) : type; } } } @@ -24228,7 +25833,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -24404,11 +26009,12 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && areAllOuterTypeParametersApplied(originalBaseType)) { - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; @@ -24572,77 +26178,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 || + return expr.kind === 9 || expr.kind === 8 || expr.kind === 192 && expr.operator === 38 && expr.operand.kind === 8 || - expr.kind === 71 && !!symbol.exports.get(expr.text); + expr.kind === 71 && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 : 1; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 && !(type.flags & 65536) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); + if (enumType_1.flags & 65536) { + enumType_1.flags |= 256; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -24874,7 +26483,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -24951,8 +26560,8 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type = types_2[_i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -25096,7 +26705,7 @@ var ts; var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); @@ -25216,6 +26825,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 ? getConstraintOfTypeParameter(type) : type.flags & 524288 ? getConstraintOfIndexedAccess(type) : @@ -25272,8 +26902,8 @@ var ts; if (t.flags & 196608) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -25315,7 +26945,7 @@ var ts; var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 ? globalStringType : - t.flags & 340 ? globalNumberType : + t.flags & 84 ? globalNumberType : t.flags & 136 ? globalBooleanType : t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : t.flags & 16777216 ? emptyObjectType : @@ -25329,12 +26959,12 @@ var ts; var commonFlags = isUnion ? 0 : 67108864; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -25400,7 +27030,7 @@ var ts; } function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); - return property && !(getCheckFlags(property) & 16) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; } function getPropertyOfType(type, name) { type = getApparentType(type); @@ -25763,8 +27393,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -25891,8 +27522,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -25922,7 +27553,7 @@ var ts; function getTypeReferenceArity(type) { return ts.length(type.target.typeParameters); } - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -25934,7 +27565,7 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -25954,7 +27585,7 @@ var ts; } return instantiation; } - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -25966,7 +27597,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -26003,14 +27633,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 | 64)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 && node.kind === 277) { return getTypeOfSymbol(symbol); @@ -26069,16 +27700,16 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } links.resolvedSymbol = symbol; links.resolvedType = type; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -26300,14 +27931,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -26315,8 +27946,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -26437,8 +28068,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -26489,9 +28120,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -26521,12 +28152,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & (32 | 64 | 256) ? - indexType.text : + var propName = indexType.flags & 96 ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -26541,11 +28172,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 340 | 512)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340) && getIndexInfoOfType(objectType, 1) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || getIndexInfoOfType(objectType, 0) || undefined; if (indexInfo) { @@ -26570,7 +28201,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 | 64)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 | 4)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -26702,7 +28333,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -26719,11 +28350,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 67108864) { + if (rightProp.flags & 67108864) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -26750,15 +28381,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 && !(type.flags & 1048576)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576, type.text); + var freshType = createLiteralType(type.flags | 1048576, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -26769,11 +28401,13 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -27028,7 +28662,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { var links = getSymbolLinks(symbol); symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); @@ -27439,29 +29073,27 @@ var ts; type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 65536) !== (target.flags & 65536)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 128)); } enumRelation.set(id, false); return false; @@ -27472,42 +29104,47 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192) + var s = source.flags; + var t = target.flags; + if (t & 8192) return false; - if (target.flags & 1 || source.flags & 8192) + if (t & 1 || s & 8192) return true; - if (source.flags & 262178 && target.flags & 2) + if (s & 262178 && t & 2) return true; - if (source.flags & 340 && target.flags & 4) + if (s & 32 && s & 256 && + t & 32 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 136 && target.flags & 8) + if (s & 84 && t & 4) return true; - if (source.flags & 256 && target.flags & 16 && source.baseType === target) + if (s & 64 && s & 256 && + t & 64 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 && t & 8) return true; - if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) + if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) + if (s & 256 && t & 256) { + if (s & 65536 && t & 65536 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 && t & 224 && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 && (!strictNullChecks || t & (2048 | 1024))) return true; - if (source.flags & 32768 && target.flags & 16777216) + if (s & 4096 && (!strictNullChecks || t & 4096)) + return true; + if (s & 32768 && t & 16777216) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) + if (s & 1) return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -27691,24 +29328,6 @@ var ts; } return 0; } - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - return true; - } - } - else if (type.flags & 196608) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(source.flags & 33554432); @@ -28057,10 +29676,10 @@ var ts; } } else if (!(targetProp.flags & 16777216)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { - if (getCheckFlags(sourceProp) & 256) { + if (ts.getCheckFlags(sourceProp) & 256) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -28157,23 +29776,34 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } - return 0; } return result; } @@ -28284,7 +29914,7 @@ var ts; } } function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6) { + if (ts.getCheckFlags(prop) & 6) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -28307,11 +29937,11 @@ var ts; }); } function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } function isAbstractConstructorType(type) { @@ -28350,8 +29980,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -28429,8 +30059,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -28438,8 +30068,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -28462,7 +30092,7 @@ var ts; return getUnionType(types, true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -28502,27 +30132,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 | 2048 | 4096)) !== 0; + return (type.flags & (224 | 2048 | 4096)) !== 0; } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 ? stringType : - type.flags & 64 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 ? stringType : + type.flags & 64 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 && type.flags & 1048576 ? stringType : - type.flags & 64 && type.flags & 1048576 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 && type.flags & 1048576 ? stringType : + type.flags & 64 && type.flags & 1048576 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function isTupleType(type) { @@ -28530,43 +30160,43 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; } function getFalsyFlags(type) { return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 ? type.text === "" ? 32 : 0 : - type.flags & 64 ? type.text === "0" ? 64 : 0 : + type.flags & 32 ? type.value === "" ? 32 : 0 : + type.flags & 64 ? type.value === 0 ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : type.flags & 7406; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178) - types.push(emptyStringType); - if (flags & 340) - types.push(zeroType); - if (flags & 136) - types.push(falseType); - if (flags & 1024) - types.push(voidType); - if (flags & 2048) - types.push(undefinedType); - if (flags & 4096) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 ? emptyStringType : + type.flags & 4 ? zeroType : + type.flags & 8 || type === falseType ? falseType : + type.flags & (1024 | 2048 | 4096) || + type.flags & 32 && type.value === "" || + type.flags & 64 && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 | 4096); + return missing === 0 ? type : + missing === 2048 ? getUnionType([type, undefinedType]) : + missing === 4096 ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; } @@ -28711,7 +30341,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { @@ -28788,7 +30418,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -28821,20 +30451,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -28847,7 +30467,7 @@ var ts; } return; } - if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 16 && target.flags & 16) || + if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 256 && target.flags & 256) || source.flags & 131072 && target.flags & 131072) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -28935,26 +30555,25 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + var isNonConstructorObject = target.flags & 32768 && + !(getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -29037,8 +30656,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -29113,7 +30732,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -29123,7 +30742,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99) { return "0"; @@ -29188,7 +30807,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2) { + if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); } @@ -29248,8 +30867,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -29265,15 +30884,16 @@ var ts; return strictNullChecks ? 4079361 : 4194049; } if (flags & 32) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 : 1982209 : - type.text === "" ? 3145473 : 4194049; + isEmpty ? 3030785 : 1982209 : + isEmpty ? 3145473 : 4194049; } if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } - if (flags & (64 | 256)) { - var isZero = type.text === "0"; + if (flags & 64) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 : 1982082 : isZero ? 3145346 : 4193922; @@ -29475,7 +31095,7 @@ var ts; } return true; } - if (source.flags & 256 && target.flags & 16 && source.baseType === target) { + if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -29498,8 +31118,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -29568,8 +31188,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -29595,7 +31215,7 @@ var ts; parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 | 2048); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -29621,7 +31241,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -29741,7 +31361,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | 2048)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -30174,6 +31794,22 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 || + parent.kind === 181 && parent.expression === node || + parent.kind === 180 && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144); + } + function getDeclaredOrApparentType(symbol, node) { + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -30228,7 +31864,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -30258,12 +31894,12 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048); + getNullableType(type, 2048); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -30958,8 +32594,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -31050,7 +32686,7 @@ var ts; return name.kind === 144 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -31065,7 +32701,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 262178 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 | 262178 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -31203,6 +32839,8 @@ var ts; } if (spread.flags & 32768) { spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; spread.symbol = node.symbol; } return spread; @@ -31262,6 +32900,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -31279,6 +32921,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255); @@ -31288,37 +32933,37 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; if (child.kind === 10) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); @@ -31328,9 +32973,8 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } var childrenPropSymbol = createSymbol(4 | 134217728, jsxChildrenPropertyName); @@ -31340,11 +32984,15 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, undefined, undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 33554432 | 4194304 | freshObjectLiteralFlag; + result.flags |= 33554432 | 4194304; result.objectFlags |= 128; return result; } @@ -31399,7 +33047,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -31433,6 +33092,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 65536)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { @@ -31442,6 +33115,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { @@ -31467,6 +33141,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -31512,7 +33187,7 @@ var ts; else if (elementType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -31670,6 +33345,24 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + return true; + } + } + else if (targetType.flags & 196608) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : @@ -31681,7 +33374,16 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -31699,36 +33401,18 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 ? flags : flags & ~28; - } - if (getCheckFlags(s) & 6) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 ? 8 : - checkFlags & 64 ? 4 : - 16; - var staticModifier = checkFlags & 512 ? 32 : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216) { - return 4 | 32; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || getCheckFlags(symbol) & 4); + return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); } function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 || node.kind === 226 ? node.name : node.right; - if (getCheckFlags(prop) & 256) { + if (ts.getCheckFlags(prop) & 256) { error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } @@ -31803,42 +33487,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 && !(containingType.flags & 8190)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (getCheckFlags(prop) & 1) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -31874,7 +33522,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -31890,6 +33538,107 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + if (ts.getCheckFlags(prop) & 1) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 ? node.expression @@ -31997,7 +33746,13 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183) { checkExpression(node.template); } @@ -32020,8 +33775,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -32108,7 +33863,7 @@ var ts; return false; } if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } if (!signature.hasRestParameter && argCount > signature.parameters.length) { return false; @@ -32344,7 +34099,7 @@ var ts; case 71: case 8: case 9: - return getLiteralTypeForText(32, element.name.text); + return getLiteralType(element.name.text); case 144: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512)) { @@ -32422,7 +34177,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183; var isDecorator = node.kind === 147; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -32450,7 +34205,7 @@ var ts; var candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -32491,25 +34246,56 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -32519,14 +34305,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -32657,7 +34435,7 @@ var ts; } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } if (isTypeAny(expressionType)) { @@ -32784,8 +34562,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -32929,7 +34707,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048); + return getNullableType(type, 2048); } } return type; @@ -32993,10 +34771,10 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 || - parameter.valueDeclaration.name.kind === 175)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -33280,15 +35058,15 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { error(operand, diagnostic); return false; } return true; } function isReadonlySymbol(symbol) { - return !!(getCheckFlags(symbol) & 8 || - symbol.flags & 4 && getDeclarationModifierFlagsFromSymbol(symbol) & 64 || + return !!(ts.getCheckFlags(symbol) & 8 || + symbol.flags & 4 && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 || symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || symbol.flags & 98304 && !(symbol.flags & 65536) || symbol.flags & 8); @@ -33368,7 +35146,7 @@ var ts; return silentNeverType; } if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37: @@ -33411,8 +35189,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -33426,8 +35204,8 @@ var ts; } if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -33436,8 +35214,8 @@ var ts; } if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -33472,7 +35250,7 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 | 512))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { @@ -33744,7 +35522,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { + if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { resultType = numberType; } else { @@ -33798,7 +35576,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53: return getTypeFacts(leftType) & 1048576 ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54: return getTypeFacts(leftType) & 2097152 ? @@ -33880,12 +35658,12 @@ var ts; var func = ts.getContainingFunction(node); var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 4096); - } + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256); } } @@ -33925,9 +35703,9 @@ var ts; } switch (node.kind) { case 9: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: return trueType; case 86: @@ -33981,7 +35759,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 | 262144)); + return maybeTypeOfKind(contextualType, (224 | 262144)); } return false; } @@ -34278,17 +36056,14 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - if (languageVersion < 2) { - checkExternalEmitHelpers(node, 128); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); } - } - if ((functionFlags & 5) === 1) { - if (functionFlags & 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 2048); + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); } - else if (languageVersion < 2) { + if ((functionFlags & 3) !== 0 && languageVersion < 2) { checkExternalEmitHelpers(node, 128); } } @@ -34311,7 +36086,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5) === 1) { + if ((functionFlags_1 & (4 | 1)) === 1) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -34334,6 +36109,13 @@ var ts; } } function checkClassForDuplicateDeclarations(node) { + var Declaration; + (function (Declaration) { + Declaration[Declaration["Getter"] = 1] = "Getter"; + Declaration[Declaration["Setter"] = 2] = "Setter"; + Declaration[Declaration["Method"] = 4] = "Method"; + Declaration[Declaration["Property"] = 3] = "Property"; + })(Declaration || (Declaration = {})); var instanceNames = ts.createMap(); var staticNames = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { @@ -34425,7 +36207,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -34499,7 +36281,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -34637,7 +36420,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { + if (type.flags & 16 && getNodeLinks(node).resolvedSymbol.flags & 8) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -34676,7 +36459,7 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 340)) { + if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1)) { return type; @@ -34726,16 +36509,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 | 16)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -34746,7 +36529,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -34854,7 +36637,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && @@ -34867,8 +36650,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -34917,11 +36700,12 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -35117,7 +36901,9 @@ var ts; checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 ? 793064 : 1920) | 8388608, undefined, undefined); if (rootSymbol @@ -35127,6 +36913,43 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167: + case 166: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + return undefined; + } + if (commonEntityName) { + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168: + return getEntityNameForDecoratorMetadata(node.type); + case 159: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -35153,7 +36976,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -35162,15 +36985,15 @@ var ts; case 154: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -35283,15 +37106,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -35369,7 +37193,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -35431,7 +37255,7 @@ var ts; if (getNodeCheckFlags(current) & 4) { var isDeclaration_1 = node.kind !== 71; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -35445,7 +37269,7 @@ var ts; if (getNodeCheckFlags(current) & 8) { var isDeclaration_2 = node.kind !== 71; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -35641,7 +37465,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -35747,11 +37571,12 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216) { if (node.awaitModifier) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 8192); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); } } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } } @@ -36201,11 +38026,14 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -36420,7 +38248,7 @@ var ts; } } function getTargetSymbol(s) { - return getCheckFlags(s) & 1 ? s.target : s; + return ts.getCheckFlags(s) & 1 ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -36439,7 +38267,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { @@ -36454,13 +38282,10 @@ var ts; } } else { - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { continue; } - if ((baseDeclarationFlags & 32) !== (derivedDeclarationFlags & 32)) { - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { continue; } @@ -36479,7 +38304,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -36562,88 +38387,81 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); + nodeLinks.flags |= 16384; var autoValue = 0; - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37: return value_1; case 38: return -value_1; case 52: return ~value_1; } - return undefined; - case 194: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49: return left | right; case 48: return left & right; case 46: return left >> right; @@ -36656,75 +38474,53 @@ var ts; case 38: return left - right; case 42: return left % right; } - return undefined; - case 8: - checkGrammarNumericLiteral(e); - return +e.text; - case 185: - return evalConstant(e.expression); - case 71: - case 180: - case 179: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71) { - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9: + return expr.text; + case 8: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185: + return evaluate(expr.expression); + case 71: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180: + case 179: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384) { + var name = expr.kind === 179 ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - var current = expression; - while (current) { - if (current.kind === 71) { - break; - } - else if (current.kind === 179) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - if (member === propertyDecl) { - return undefined; - } - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return 0; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 || + node.kind === 179 && isConstantMemberAccess(node.expression) || + node.kind === 180 && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -36747,7 +38543,7 @@ var ts; if (enumSymbol.declarations.length > 1) { ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -36972,6 +38768,9 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + if (node.kind === 246 && compilerOptions.isolatedModules && !(target.flags & 107455)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -37618,7 +39417,7 @@ var ts; if (isInsideWithStatementBody(node)) { return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { return getSymbolOfNode(node.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { @@ -37731,7 +39530,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -37793,16 +39592,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728) { if (symbol.leftSpread) { @@ -38063,7 +39862,7 @@ var ts; else if (isTypeOfKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340)) { + else if (isTypeOfKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178)) { @@ -38091,7 +39890,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -38103,15 +39902,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -38190,7 +39980,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -38337,7 +40126,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 8192; helper <<= 1) { + for (var helper = 1; helper <= 16384; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); @@ -38364,9 +40153,10 @@ var ts; case 256: return "__values"; case 512: return "__read"; case 1024: return "__spread"; - case 2048: return "__asyncGenerator"; - case 4096: return "__asyncDelegator"; - case 8192: return "__asyncValues"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -39395,6 +41185,17 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242: + case 246: + if (name.parent.propertyName) { + return true; + } + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -39505,49 +41306,59 @@ var ts; if ((kind > 0 && kind <= 142) || kind === 169) { return node; } - switch (node.kind) { - case 206: - case 209: - case 200: - case 225: - case 298: - case 247: - return node; + switch (kind) { + case 71: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - case 160: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 145: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); - case 159: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 148: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 158: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170: @@ -39558,20 +41369,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - case 145: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 148: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 174: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 175: @@ -39608,12 +41405,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196: @@ -39630,6 +41427,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); case 205: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 207: @@ -39674,6 +41473,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233: @@ -39682,6 +41485,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238: @@ -39706,8 +41511,6 @@ var ts; return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 249: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251: @@ -39716,6 +41519,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256: @@ -39740,6 +41545,8 @@ var ts; return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); case 296: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; } @@ -39795,6 +41602,13 @@ var ts; case 147: result = reduceNode(node.expression, cbNode, result); break; + case 148: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -40133,6 +41947,9 @@ var ts; case 296: result = reduceNode(node.expression, cbNode, result); break; + case 297: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -40231,6 +42048,11 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var FlattenLevel; + (function (FlattenLevel) { + FlattenLevel[FlattenLevel["All"] = 0] = "All"; + FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest"; + })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {})); function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { var location = node; var value; @@ -40550,6 +42372,12 @@ var ts; var ts; (function (ts) { var USE_NEW_TYPE_METADATA_FORMAT = false; + var TypeScriptSubstitutionFlags; + (function (TypeScriptSubstitutionFlags) { + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; + })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); function transformTypeScript(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -40572,7 +42400,7 @@ var ts; var applicableSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -41361,15 +43189,10 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || serializedUnion.text !== serializedIndividual.text) { @@ -41656,7 +43479,12 @@ var ts; } function transformEnumMember(member) { var name = getExpressionForPropertyName(member, false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } function transformEnumMemberDeclarationValue(member) { var value = resolver.getConstantValue(member); @@ -41703,9 +43531,9 @@ var ts; return false; } function addVarForEnumOrModuleDeclaration(statements, node) { - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, false, true)) - ]); + ], currentScope.kind === 265 ? 0 : 1)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -41838,7 +43666,7 @@ var ts; } function visitExportDeclaration(node) { if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { return undefined; @@ -42130,6 +43958,10 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var ES2017SubstitutionFlags; + (function (ES2017SubstitutionFlags) { + ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); function transformES2017(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; var resolver = context.getEmitResolver(); @@ -42144,7 +43976,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -42371,6 +44203,10 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var ESNextSubstitutionFlags; + (function (ESNextSubstitutionFlags) { + ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); function transformESNext(context) { var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -42385,7 +44221,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -42453,19 +44289,14 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), node), node); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -42592,6 +44423,9 @@ var ts; } return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); } + function awaitAsYield(expression) { + return ts.createYield(undefined, enclosingFunctionFlags & 1 ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); @@ -42599,19 +44433,17 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(undefined); - var values = createAsyncValuesHelper(context, expression, node.expression); - var next = ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), - ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), node), 256); + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, awaitAsYield(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -42620,12 +44452,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -42857,12 +44684,22 @@ var ts; return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ @@ -42874,11 +44711,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); } var asyncValues = { @@ -42897,7 +44734,7 @@ var ts; var compilerOptions = context.getCompilerOptions(); return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -43335,7 +45172,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -43393,6 +45230,75 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var ES2015SubstitutionFlags; + (function (ES2015SubstitutionFlags) { + ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; + ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; + })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); + var SuperCaptureResult; + (function (SuperCaptureResult) { + SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; + })(SuperCaptureResult || (SuperCaptureResult = {})); + var HierarchyFacts; + (function (HierarchyFacts) { + HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function"; + HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody"; + HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement"; + HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis"; + HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement"; + HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel"; + HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block"; + HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement"; + HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock"; + HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; + HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; + HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; + HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 4032] = "BlockScopeExcludes"; + HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes"; + HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; + HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; + HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; + HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 256] = "DoOrWhileStatementIncludes"; + HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes"; + HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 1280] = "ForStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 3008] = "ForStatementExcludes"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 2304] = "ForInOrForOfStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 1984] = "ForInOrForOfStatementExcludes"; + HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes"; + HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; + HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; + HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; + HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; + HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; + HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; + })(HierarchyFacts || (HierarchyFacts = {})); function transformES2015(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); @@ -43408,7 +45314,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -44271,12 +46177,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { updated = undefined; @@ -45164,7 +47071,7 @@ var ts; if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -45313,6 +47220,51 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var OpCode; + (function (OpCode) { + OpCode[OpCode["Nop"] = 0] = "Nop"; + OpCode[OpCode["Statement"] = 1] = "Statement"; + OpCode[OpCode["Assign"] = 2] = "Assign"; + OpCode[OpCode["Break"] = 3] = "Break"; + OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue"; + OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse"; + OpCode[OpCode["Yield"] = 6] = "Yield"; + OpCode[OpCode["YieldStar"] = 7] = "YieldStar"; + OpCode[OpCode["Return"] = 8] = "Return"; + OpCode[OpCode["Throw"] = 9] = "Throw"; + OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; + })(OpCode || (OpCode = {})); + var BlockAction; + (function (BlockAction) { + BlockAction[BlockAction["Open"] = 0] = "Open"; + BlockAction[BlockAction["Close"] = 1] = "Close"; + })(BlockAction || (BlockAction = {})); + var CodeBlockKind; + (function (CodeBlockKind) { + CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception"; + CodeBlockKind[CodeBlockKind["With"] = 1] = "With"; + CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch"; + CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop"; + CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled"; + })(CodeBlockKind || (CodeBlockKind = {})); + var ExceptionBlockState; + (function (ExceptionBlockState) { + ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try"; + ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch"; + ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally"; + ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done"; + })(ExceptionBlockState || (ExceptionBlockState = {})); + var Instruction; + (function (Instruction) { + Instruction[Instruction["Next"] = 0] = "Next"; + Instruction[Instruction["Throw"] = 1] = "Throw"; + Instruction[Instruction["Return"] = 2] = "Return"; + Instruction[Instruction["Break"] = 3] = "Break"; + Instruction[Instruction["Yield"] = 4] = "Yield"; + Instruction[Instruction["YieldStar"] = 5] = "YieldStar"; + Instruction[Instruction["Catch"] = 6] = "Catch"; + Instruction[Instruction["Endfinally"] = 7] = "Endfinally"; + })(Instruction || (Instruction = {})); function getInstructionName(instruction) { switch (instruction) { case 2: return "return"; @@ -45357,8 +47309,7 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; } currentSourceFile = node; @@ -46974,7 +48925,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -47137,9 +49088,9 @@ var ts; return visitFunctionDeclaration(node); case 229: return visitClassDeclaration(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return node; @@ -47643,9 +49594,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -48158,9 +50107,9 @@ var ts; return visitCatchClause(node); case 207: return visitBlock(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -48451,7 +50400,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -48522,6 +50471,18 @@ var ts; return ts.transformModule; } } + var TransformationState; + (function (TransformationState) { + TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized"; + TransformationState[TransformationState["Initialized"] = 1] = "Initialized"; + TransformationState[TransformationState["Completed"] = 2] = "Completed"; + TransformationState[TransformationState["Disposed"] = 3] = "Disposed"; + })(TransformationState || (TransformationState = {})); + var SyntaxKindFeatureFlags; + (function (SyntaxKindFeatureFlags) { + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution"; + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications"; + })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {})); function getTransformers(compilerOptions, customTransformers) { var jsx = compilerOptions.jsx; var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -48554,7 +50515,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299); + var enabledSyntaxKindFeatures = new Array(300); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -48612,7 +50573,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } function enableSubstitution(kind) { ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); @@ -49387,7 +51348,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencesOutput = ""; @@ -49412,11 +51373,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -49820,8 +51781,7 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -49834,23 +51794,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -49860,12 +51827,6 @@ var ts; var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -49935,7 +51896,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && !noDeclare) { + else if (node.kind !== 230 && needsDeclare) { write("declare "); } } @@ -50163,7 +52124,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -50260,7 +52221,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -50272,12 +52233,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 229) { @@ -50291,7 +52246,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -50306,6 +52261,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128)) { @@ -50313,15 +52281,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); write(" {"); writeLine(); increaseIndent(); @@ -50342,7 +52317,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, false); + emitHeritageClause(interfaceExtendsTypes, false); } write(" {"); writeLine(); @@ -50394,7 +52369,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 || node.kind === 148) { + else if (node.kind === 149 || node.kind === 148 || + (node.kind === 146 && ts.hasModifier(node.parent, 8))) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -50402,7 +52378,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 229 || node.kind === 146) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -50597,6 +52573,11 @@ var ts; write("["); } else { + if (node.kind === 152 && ts.hasModifier(node, 8)) { + write("();"); + writeLine(); + return; + } if (node.kind === 156 || node.kind === 161) { write("new "); } @@ -50855,7 +52836,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { declFileName = referencedFile.fileName; } else { @@ -51013,7 +52994,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -51044,7 +53025,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -51130,7 +53111,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -51206,7 +53189,7 @@ var ts; function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -51406,7 +53389,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -51426,7 +53409,7 @@ var ts; case 97: case 101: case 99: - writeTokenText(kind); + writeTokenNode(node); return; case 177: return emitArrayLiteralExpression(node); @@ -51488,6 +53471,8 @@ var ts; return emitJsxSelfClosingElement(node); case 296: return emitPartiallyEmittedExpression(node); + case 297: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -51513,6 +53498,7 @@ var ts; } function emitIdentifier(node) { write(getTextOfNode(node, false)); + emitTypeArguments(node, node.typeArguments); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -51535,6 +53521,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -51649,7 +53636,9 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65); + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 ? 448 : 65); + } write("}"); } function emitArrayType(node) { @@ -51687,9 +53676,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -51700,8 +53695,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -51714,7 +53714,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432); + emitList(node, elements, ts.getEmitFlags(node) & 1 ? 272 : 432); write("}"); } } @@ -51790,7 +53790,7 @@ var ts; } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -51881,7 +53881,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -52560,6 +54560,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272); + } function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { for (var i = 0; i < statements.length; i++) { var statement = statements[i]; @@ -52808,6 +54811,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -52985,7 +54997,9 @@ var ts; if (node.kind === 9 && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -53164,6 +55178,77 @@ var ts; function getClosingBracket(format) { return brackets[format & 7680][1]; } + var TempFlags; + (function (TempFlags) { + TempFlags[TempFlags["Auto"] = 0] = "Auto"; + TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; + TempFlags[TempFlags["_i"] = 268435456] = "_i"; + })(TempFlags || (TempFlags = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; + ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; + ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; + ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + ListFormat[ListFormat["Indented"] = 64] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + ListFormat[ListFormat["Braces"] = 512] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; + ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; + ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementChildren"] = 131072] = "JsxElementChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 26960] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 26960] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 1360] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; + })(ListFormat || (ListFormat = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -53352,6 +55437,83 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); + lineContent = lineContent.replace("\t", " "); + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -53401,6 +55563,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -53443,7 +55606,8 @@ var ts; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); if (typeReferences.length) { @@ -53492,7 +55656,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -53525,45 +55690,64 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { + if (structuralIsReused === 0 && !file.ambientModuleNames.length) { return resolveModuleNamesWorker(moduleNames, containingFile); } + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } var unknownModuleNames; var result; var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - var isKnownToResolveToAmbientModule = false; + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - result = new Array(moduleNames.length); - unknownModuleNames = moduleNames.slice(0, i); - } - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - unknownModuleNames.push(moduleName); + else { + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; + if (!result) { + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -53572,15 +55756,12 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -53599,67 +55780,73 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0; } var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 | 1))); var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0; } var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - newSourceFile = oldSourceFile; - } newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -53667,11 +55854,16 @@ var ts; var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; } for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); @@ -53683,8 +55875,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { return { @@ -54024,7 +56215,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -54055,7 +56246,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -54096,13 +56286,13 @@ var ts; } break; case 233: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { (ambientModules || (ambientModules = [])).push(moduleName.text); } var body = node.body; @@ -54125,45 +56315,50 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -54299,10 +56494,10 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -54351,7 +56546,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -54448,12 +56643,12 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -54685,6 +56880,7 @@ var ts; "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -55536,49 +57732,28 @@ var ts; if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + if (exclude) { + json.exclude = exclude; } - if (include && !json["include"]) { - json["include"] = include; + if (files) { + json.files = files; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } + return options; + })(); options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -55588,37 +57763,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -55649,9 +57794,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; @@ -55668,9 +57810,66 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -55915,8 +58114,8 @@ var ts; reportDiagnosticWorker(diagnostic, host || defaultFormatDiagnosticsHost); } function reportDiagnostics(diagnostics, host) { - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; reportDiagnostic(diagnostic, host); } } @@ -55949,73 +58148,8 @@ var ts; function reportDiagnosticSimply(diagnostic, host) { ts.sys.write(ts.formatDiagnostics([diagnostic], host)); } - var redForegroundEscapeSequence = "\u001b[91m"; - var yellowForegroundEscapeSequence = "\u001b[93m"; - var blueForegroundEscapeSequence = "\u001b[93m"; - var gutterStyleSequence = "\u001b[100;30m"; - var gutterSeparator = " "; - var resetEscapeSequence = "\u001b[0m"; - var ellipsis = "..."; - function getCategoryFormat(category) { - switch (category) { - case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; - case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; - case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; - } - } - function formatAndReset(text, formatStyle) { - return formatStyle + text + resetEscapeSequence; - } function reportDiagnosticWithColorAndContext(diagnostic, host) { - var output = ""; - if (diagnostic.file) { - var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; - var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; - var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; - var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; - var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; - var gutterWidth = (lastLine + 1 + "").length; - if (hasMoreThanFiveLines) { - gutterWidth = Math.max(ellipsis.length, gutterWidth); - } - output += ts.sys.newLine; - for (var i = firstLine; i <= lastLine; i++) { - if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; - i = lastLine - 1; - } - var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); - var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; - var lineContent = file.text.slice(lineStart, lineEnd); - lineContent = lineContent.replace(/\s+$/g, ""); - lineContent = lineContent.replace("\t", " "); - output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + ts.sys.newLine; - output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += redForegroundEscapeSequence; - if (i === firstLine) { - var lastCharForLine = i === lastLine ? lastLineChar : undefined; - output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); - } - else if (i === lastLine) { - output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); - } - else { - output += lineContent.replace(/./g, "~"); - } - output += resetEscapeSequence; - output += ts.sys.newLine; - } - output += ts.sys.newLine; - output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; - } - var categoryColor = getCategoryFormat(diagnostic.category); - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); - output += ts.sys.newLine + ts.sys.newLine; - ts.sys.write(output); + ts.sys.write(ts.formatDiagnosticsWithColorAndContext([diagnostic], host) + ts.sys.newLine + ts.sys.newLine); } function reportWatchDiagnostic(diagnostic) { var output = new Date().toLocaleTimeString() + " - "; @@ -56482,3 +58616,5 @@ if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnviron ts.sys.tryEnableSourceMapsForHost(); } ts.executeCommandLine(ts.sys.args); + +//# sourceMappingURL=tsc.js.map diff --git a/lib/tsserver.js b/lib/tsserver.js index 05f4c1e5fd1..0e99abde9da 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -332,9 +332,10 @@ var ts; SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; @@ -469,6 +470,12 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -478,12 +485,20 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { @@ -604,6 +619,11 @@ var ts; SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); var CheckFlags; (function (CheckFlags) { CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; @@ -671,21 +691,21 @@ var ts; TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; - TypeFlags[TypeFlags["Narrowable"] = 17810431] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; @@ -1011,6 +1031,7 @@ var ts; EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1025,14 +1046,17 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1288,6 +1312,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; function every(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1492,6 +1525,28 @@ var ts; return result; } ts.flatMap = flatMap; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -2516,6 +2571,10 @@ var ts; return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -3571,6 +3630,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -3678,7 +3738,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -3873,6 +3933,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4168,6 +4236,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -4213,6 +4282,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4294,6 +4365,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -4322,12 +4396,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -4611,6 +4684,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -4744,12 +4819,18 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -4779,7 +4860,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -5164,9 +5244,7 @@ var ts; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -5323,26 +5401,28 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; } @@ -5549,10 +5629,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 && isConst(node); } @@ -5804,6 +5880,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160: + case 161: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151: @@ -6028,6 +6113,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 || node.kind === 182; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183) { return node.tag; @@ -6581,21 +6670,46 @@ var ts; } ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { - if (name.kind !== 71 && name.kind !== 9 && name.kind !== 8) { - return false; + switch (name.kind) { + case 71: + case 9: + case 8: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 || parent.kind === 246) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0: + case 2: + return undefined; + case 1: + if (lhs.kind === 71) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4: + case 5: + return lhs.name; + case 3: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 144 && @@ -6695,21 +6809,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -6737,12 +6849,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4; + } var flags = 0; switch (node.kind) { case 228: @@ -6787,7 +6900,8 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -7062,6 +7176,8 @@ var ts; return 2; case 198: return 1; + case 297: + return 0; default: return -1; } @@ -7165,12 +7281,13 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -7259,7 +7376,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -7311,7 +7428,7 @@ var ts; } ts.getSourceFilesToEmit = getSourceFilesToEmit; function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { @@ -7800,13 +7917,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 1: + return lineFeed; } - else if (options.newLine === 1) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -8054,10 +8171,6 @@ var ts; return node.kind === 71; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { return isIdentifier(node) && node.autoGenerateKind > 0; } @@ -8125,9 +8238,20 @@ var ts; || kind === 153 || kind === 154 || kind === 157 - || kind === 206; + || kind === 206 + || kind === 247; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 + || kind === 155 + || kind === 148 + || kind === 150 + || kind === 157 + || kind === 247; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 @@ -8325,6 +8449,7 @@ var ts; || kind === 198 || kind === 202 || kind === 200 + || kind === 297 || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -8411,6 +8536,10 @@ var ts; return node.kind === 237; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239; } @@ -8433,6 +8562,10 @@ var ts; return node.kind === 246; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 || node.kind === 232; } @@ -8504,8 +8637,8 @@ var ts; || kind === 213 || kind === 220 || kind === 295 - || kind === 298 - || kind === 297; + || kind === 299 + || kind === 298; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -8621,6 +8754,48 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + } + if (getCheckFlags(s) & 6) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 ? 8 : + checkFlags & 64 ? 4 : + 16; + var staticModifier = checkFlags & 512 ? 32 : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216) { + return 4 | 32; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -9424,9 +9599,10 @@ var ts; } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -10536,15 +10712,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; node.autoGenerateKind = 0; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; function createTempVariable(recordTempVariable) { var name = createIdentifier(""); @@ -10632,237 +10817,12 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170); - typeOperatorNode.operator = 127; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -10873,42 +10833,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146); node.decorators = asNodeArray(decorators); @@ -10945,6 +10869,26 @@ var ts; : node; } ts.updateDecorator = updateDecorator; + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149); node.decorators = asNodeArray(decorators); @@ -10966,7 +10910,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -10979,7 +10940,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -10989,7 +10950,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -11057,6 +11018,249 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170); + node.operator = 127; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174); node.elements = createNodeArray(elements); @@ -11102,9 +11306,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -11117,9 +11320,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -11167,9 +11369,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -11359,10 +11561,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -11489,6 +11691,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205); node.expression = expression; @@ -11503,6 +11718,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206); + } + ts.createSemicolonClassElement = createSemicolonClassElement; function createBlock(statements, multiLine) { var block = createSynthesizedNode(207); block.statements = createNodeArray(statements); @@ -11512,7 +11731,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -11532,35 +11751,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209); } @@ -11779,6 +11969,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227); + node.flags |= flags & 3; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228); node.decorators = asNodeArray(decorators); @@ -11827,6 +12050,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232); node.decorators = asNodeArray(decorators); @@ -11847,7 +12112,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233); - node.flags |= flags; + node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -11888,6 +12153,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237); node.decorators = asNodeArray(decorators); @@ -11918,7 +12195,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -12104,19 +12382,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253); node.name = name; @@ -12131,6 +12396,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255); node.expression = expression; @@ -12156,20 +12433,6 @@ var ts; : node; } ts.updateJsxExpression = updateJsxExpression; - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257); node.expression = ts.parenthesizeExpressionForList(expression); @@ -12178,10 +12441,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -12191,12 +12454,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -12205,10 +12480,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer) { @@ -12220,10 +12495,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -12234,10 +12509,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -12247,10 +12522,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; function createEnumMember(name, initializer) { @@ -12345,14 +12619,14 @@ var ts; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(299); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(298); node.emitNode = {}; node.original = original; return node; @@ -12373,6 +12647,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266); node.sourceFiles = sourceFiles; @@ -12683,6 +12980,25 @@ var ts; } })(ts || (ts = {})); (function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -12923,7 +13239,9 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -13030,9 +13348,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -13143,16 +13462,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 185) { @@ -13321,6 +13630,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166: + case 167: + case 160: + case 161: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { var clone_1 = ts.getMutableClone(originalOuterExpression); @@ -13473,7 +13810,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -14130,6 +14467,8 @@ var ts; return visitNode(cbNode, node.expression); case 247: return visitNodes(cbNodes, node.decorators); + case 297: + return visitNodes(cbNodes, node.elements); case 249: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -18472,6 +18811,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -19232,7 +19573,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -19260,7 +19601,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { return true; } else { @@ -19293,19 +19634,20 @@ var ts; } } function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144) { - var nameExpression = node.name.expression; + if (name.kind === 144) { + var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152: @@ -19401,9 +19743,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -21053,7 +21395,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { @@ -21068,7 +21410,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -21083,7 +21425,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -21096,7 +21438,7 @@ var ts; return bindAnonymousDeclaration(node, 16, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -21831,6 +22173,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -21975,13 +22318,16 @@ var ts; tryFindAmbientModuleWithoutAugmentations: function (moduleName) { return tryFindAmbientModule(moduleName, false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4, "unknown"); @@ -22054,11 +22400,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32, ""); - var zeroType = getLiteralTypeForText(64, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -22315,16 +22663,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 || source.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -22397,9 +22745,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); } @@ -22407,7 +22752,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -22435,7 +22780,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -22510,7 +22856,11 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; var result; var lastLocation; var propertyWithInvalidInitializer; @@ -22519,7 +22869,7 @@ var ts; var isInExternalModule = false; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { if (meaning & result.flags & 793064 && lastLocation.kind !== 283) { @@ -22566,12 +22916,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931)) { + if (result = lookup(moduleExports, name, meaning & 8914931)) { break loop; } break; case 232: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; @@ -22580,7 +22930,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455)) { + if (lookup(ctor.locals, name, meaning & 107455)) { propertyWithInvalidInitializer = location; } } @@ -22589,7 +22939,7 @@ var ts; case 229: case 199: case 230: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -22611,7 +22961,7 @@ var ts; case 144: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -22658,7 +23008,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -22668,7 +23018,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -22765,6 +23125,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -22796,13 +23160,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -22814,7 +23178,7 @@ var ts; if (node.kind === 237) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -22917,10 +23281,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920, false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); @@ -22936,7 +23300,7 @@ var ts; case 242: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); case 243: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236: @@ -23058,7 +23422,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -23078,6 +23442,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, true); if (ambientModule) { return ambientModule; @@ -23137,7 +23506,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -23278,7 +23646,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } function isReservedMemberName(name) { return name.charCodeAt(0) === 95 && @@ -23548,34 +23916,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3, typeNode, sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -23585,12 +23978,12 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; return undefined; @@ -23607,23 +24000,25 @@ var ts; if (type.flags & 8) { return ts.createKeywordTypeNode(122); } - if (type.flags & 16) { - var name = symbolToName(type.symbol, false); + if (type.flags & 256 && !(type.flags & 65536)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064, false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, undefined); + } + if (type.flags & 272) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } if (type.flags & (32)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); } if (type.flags & (64)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } if (type.flags & 1024) { return ts.createKeywordTypeNode(105); } @@ -23643,8 +24038,8 @@ var ts; return ts.createKeywordTypeNode(134); } if (type.flags & 16384 && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -23655,72 +24050,53 @@ var ts; ts.Debug.assert(!!(type.flags & 32768)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3) { - ts.Debug.assert(!!(type.flags & 32768)); - var name = symbolToName(type.symbol, false); + if (type.flags & 16384 || objectFlags & 3) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } - if (type.flags & 16384) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064, false).accessibility === 0) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166, unionTypeNodes); + if (type.flags & (65536 | 131072)) { + var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 ? 166 : 167, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072) { - return ts.createUnionOrIntersectionTypeNode(167, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 | 32)) { ts.Debug.assert(!!(type.flags & 32768)); return createAnonymousTypeNode(type); } if (type.flags & 262144) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -23728,12 +24104,12 @@ var ts; if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455); } else if (ts.contains(context.symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - var entityName = symbolToName(typeAlias, false); + var entityName = symbolToName(typeAlias, context, 793064, false); return ts.createTypeReferenceNode(entityName, undefined); } else { @@ -23775,41 +24151,52 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -23817,7 +24204,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -23827,48 +24214,72 @@ var ts; i++; } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - var qualifiedNamePart = symbolToName(parent, true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, undefined); + qualifiedName = ts.createQualifiedName(namePart, undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); } var properties = resolvedType.properties; if (!properties) { @@ -23877,74 +24288,121 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455, true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 ? ts.createToken(55) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); - var name = ts.getNameFromIndexInfo(indexInfo); - var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); + var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064, true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24), ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 | 16777216); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0, true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -23952,18 +24410,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -23972,20 +24430,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } function getSymbolChain(symbol, meaning, endOfChain) { @@ -24011,28 +24459,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199: + return "(Anonymous class)"; + case 186: + case 187: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -24050,12 +24499,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144)) { if (t.flags & (128 | 256)) { - var baseType = t.flags & 128 ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -24091,13 +24542,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -24140,7 +24592,7 @@ var ts; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { if (flags & 1) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -24205,12 +24657,15 @@ var ts; else if (getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 23); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 && !(type.flags & 65536)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 || type.flags & (16 | 16384)) { + else if (getObjectFlags(type) & 3 || type.flags & (272 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 512) && type.aliasSymbol && @@ -24547,7 +25002,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -24798,10 +25253,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 8388608); } var result = []; if (exportSymbol) { @@ -24922,7 +25374,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -25022,7 +25474,7 @@ var ts; return expr.kind === 177 && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; + return strictNullChecks && optional ? getNullableType(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536) { @@ -25100,6 +25552,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 ? declaration : @@ -25116,16 +25569,23 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536) { - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { @@ -25335,7 +25795,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 ? includeFalsyTypes(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 67108864 ? getNullableType(type, 2048) : type; } } } @@ -25391,7 +25851,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -25567,11 +26027,12 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && areAllOuterTypeParametersApplied(originalBaseType)) { - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; @@ -25735,77 +26196,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 || + return expr.kind === 9 || expr.kind === 8 || expr.kind === 192 && expr.operator === 38 && expr.operand.kind === 8 || - expr.kind === 71 && !!symbol.exports.get(expr.text); + expr.kind === 71 && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 : 1; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 && !(type.flags & 65536) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); + if (enumType_1.flags & 65536) { + enumType_1.flags |= 256; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -26037,7 +26501,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -26114,8 +26578,8 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type = types_2[_i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -26259,7 +26723,7 @@ var ts; var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); @@ -26379,6 +26843,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 ? getConstraintOfTypeParameter(type) : type.flags & 524288 ? getConstraintOfIndexedAccess(type) : @@ -26435,8 +26920,8 @@ var ts; if (t.flags & 196608) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -26478,7 +26963,7 @@ var ts; var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 ? globalStringType : - t.flags & 340 ? globalNumberType : + t.flags & 84 ? globalNumberType : t.flags & 136 ? globalBooleanType : t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : t.flags & 16777216 ? emptyObjectType : @@ -26492,12 +26977,12 @@ var ts; var commonFlags = isUnion ? 0 : 67108864; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -26563,7 +27048,7 @@ var ts; } function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); - return property && !(getCheckFlags(property) & 16) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; } function getPropertyOfType(type, name) { type = getApparentType(type); @@ -26926,8 +27411,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -27054,8 +27540,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -27085,7 +27571,7 @@ var ts; function getTypeReferenceArity(type) { return ts.length(type.target.typeParameters); } - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -27097,7 +27583,7 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -27117,7 +27603,7 @@ var ts; } return instantiation; } - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -27129,7 +27615,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -27166,14 +27651,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 | 64)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 && node.kind === 277) { return getTypeOfSymbol(symbol); @@ -27232,16 +27718,16 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } links.resolvedSymbol = symbol; links.resolvedType = type; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -27463,14 +27949,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -27478,8 +27964,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -27600,8 +28086,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -27652,9 +28138,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -27684,12 +28170,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & (32 | 64 | 256) ? - indexType.text : + var propName = indexType.flags & 96 ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -27704,11 +28190,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 340 | 512)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340) && getIndexInfoOfType(objectType, 1) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || getIndexInfoOfType(objectType, 0) || undefined; if (indexInfo) { @@ -27733,7 +28219,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 | 64)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 | 4)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -27865,7 +28351,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -27882,11 +28368,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 67108864) { + if (rightProp.flags & 67108864) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -27913,15 +28399,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 && !(type.flags & 1048576)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576, type.text); + var freshType = createLiteralType(type.flags | 1048576, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -27932,11 +28419,13 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -28191,7 +28680,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { var links = getSymbolLinks(symbol); symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); @@ -28602,29 +29091,27 @@ var ts; type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 65536) !== (target.flags & 65536)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 128)); } enumRelation.set(id, false); return false; @@ -28635,42 +29122,47 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192) + var s = source.flags; + var t = target.flags; + if (t & 8192) return false; - if (target.flags & 1 || source.flags & 8192) + if (t & 1 || s & 8192) return true; - if (source.flags & 262178 && target.flags & 2) + if (s & 262178 && t & 2) return true; - if (source.flags & 340 && target.flags & 4) + if (s & 32 && s & 256 && + t & 32 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 136 && target.flags & 8) + if (s & 84 && t & 4) return true; - if (source.flags & 256 && target.flags & 16 && source.baseType === target) + if (s & 64 && s & 256 && + t & 64 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 && t & 8) return true; - if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) + if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) + if (s & 256 && t & 256) { + if (s & 65536 && t & 65536 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 && t & 224 && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 && (!strictNullChecks || t & (2048 | 1024))) return true; - if (source.flags & 32768 && target.flags & 16777216) + if (s & 4096 && (!strictNullChecks || t & 4096)) + return true; + if (s & 32768 && t & 16777216) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) + if (s & 1) return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -28854,24 +29346,6 @@ var ts; } return 0; } - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - return true; - } - } - else if (type.flags & 196608) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(source.flags & 33554432); @@ -29220,10 +29694,10 @@ var ts; } } else if (!(targetProp.flags & 16777216)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { - if (getCheckFlags(sourceProp) & 256) { + if (ts.getCheckFlags(sourceProp) & 256) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -29320,23 +29794,34 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } - return 0; } return result; } @@ -29447,7 +29932,7 @@ var ts; } } function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6) { + if (ts.getCheckFlags(prop) & 6) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -29470,11 +29955,11 @@ var ts; }); } function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } function isAbstractConstructorType(type) { @@ -29513,8 +29998,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -29592,8 +30077,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -29601,8 +30086,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -29625,7 +30110,7 @@ var ts; return getUnionType(types, true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -29665,27 +30150,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 | 2048 | 4096)) !== 0; + return (type.flags & (224 | 2048 | 4096)) !== 0; } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 ? stringType : - type.flags & 64 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 ? stringType : + type.flags & 64 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 && type.flags & 1048576 ? stringType : - type.flags & 64 && type.flags & 1048576 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 && type.flags & 1048576 ? stringType : + type.flags & 64 && type.flags & 1048576 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function isTupleType(type) { @@ -29693,43 +30178,43 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; } function getFalsyFlags(type) { return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 ? type.text === "" ? 32 : 0 : - type.flags & 64 ? type.text === "0" ? 64 : 0 : + type.flags & 32 ? type.value === "" ? 32 : 0 : + type.flags & 64 ? type.value === 0 ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : type.flags & 7406; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178) - types.push(emptyStringType); - if (flags & 340) - types.push(zeroType); - if (flags & 136) - types.push(falseType); - if (flags & 1024) - types.push(voidType); - if (flags & 2048) - types.push(undefinedType); - if (flags & 4096) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 ? emptyStringType : + type.flags & 4 ? zeroType : + type.flags & 8 || type === falseType ? falseType : + type.flags & (1024 | 2048 | 4096) || + type.flags & 32 && type.value === "" || + type.flags & 64 && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 | 4096); + return missing === 0 ? type : + missing === 2048 ? getUnionType([type, undefinedType]) : + missing === 4096 ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; } @@ -29874,7 +30359,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { @@ -29951,7 +30436,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -29984,20 +30469,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -30010,7 +30485,7 @@ var ts; } return; } - if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 16 && target.flags & 16) || + if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 256 && target.flags & 256) || source.flags & 131072 && target.flags & 131072) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -30098,26 +30573,25 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + var isNonConstructorObject = target.flags & 32768 && + !(getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -30200,8 +30674,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -30276,7 +30750,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -30286,7 +30760,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99) { return "0"; @@ -30351,7 +30825,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2) { + if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); } @@ -30411,8 +30885,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -30428,15 +30902,16 @@ var ts; return strictNullChecks ? 4079361 : 4194049; } if (flags & 32) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 : 1982209 : - type.text === "" ? 3145473 : 4194049; + isEmpty ? 3030785 : 1982209 : + isEmpty ? 3145473 : 4194049; } if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } - if (flags & (64 | 256)) { - var isZero = type.text === "0"; + if (flags & 64) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 : 1982082 : isZero ? 3145346 : 4193922; @@ -30638,7 +31113,7 @@ var ts; } return true; } - if (source.flags & 256 && target.flags & 16 && source.baseType === target) { + if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -30661,8 +31136,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -30731,8 +31206,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -30758,7 +31233,7 @@ var ts; parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 | 2048); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -30784,7 +31259,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -30904,7 +31379,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | 2048)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -31337,6 +31812,22 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 || + parent.kind === 181 && parent.expression === node || + parent.kind === 180 && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144); + } + function getDeclaredOrApparentType(symbol, node) { + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -31391,7 +31882,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -31421,12 +31912,12 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048); + getNullableType(type, 2048); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -32121,8 +32612,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -32213,7 +32704,7 @@ var ts; return name.kind === 144 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -32228,7 +32719,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 262178 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 | 262178 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -32366,6 +32857,8 @@ var ts; } if (spread.flags & 32768) { spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; spread.symbol = node.symbol; } return spread; @@ -32425,6 +32918,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -32442,6 +32939,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255); @@ -32451,37 +32951,37 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; if (child.kind === 10) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); @@ -32491,9 +32991,8 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } var childrenPropSymbol = createSymbol(4 | 134217728, jsxChildrenPropertyName); @@ -32503,11 +33002,15 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, undefined, undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 33554432 | 4194304 | freshObjectLiteralFlag; + result.flags |= 33554432 | 4194304; result.objectFlags |= 128; return result; } @@ -32562,7 +33065,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -32596,6 +33110,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 65536)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { @@ -32605,6 +33133,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { @@ -32630,6 +33159,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -32675,7 +33205,7 @@ var ts; else if (elementType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -32833,6 +33363,24 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + return true; + } + } + else if (targetType.flags & 196608) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : @@ -32844,7 +33392,16 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -32862,36 +33419,18 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 ? flags : flags & ~28; - } - if (getCheckFlags(s) & 6) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 ? 8 : - checkFlags & 64 ? 4 : - 16; - var staticModifier = checkFlags & 512 ? 32 : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216) { - return 4 | 32; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || getCheckFlags(symbol) & 4); + return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); } function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 || node.kind === 226 ? node.name : node.right; - if (getCheckFlags(prop) & 256) { + if (ts.getCheckFlags(prop) & 256) { error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } @@ -32966,42 +33505,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 && !(containingType.flags & 8190)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (getCheckFlags(prop) & 1) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -33037,7 +33540,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -33053,6 +33556,107 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + if (ts.getCheckFlags(prop) & 1) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 ? node.expression @@ -33160,7 +33764,13 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183) { checkExpression(node.template); } @@ -33183,8 +33793,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -33271,7 +33881,7 @@ var ts; return false; } if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } if (!signature.hasRestParameter && argCount > signature.parameters.length) { return false; @@ -33507,7 +34117,7 @@ var ts; case 71: case 8: case 9: - return getLiteralTypeForText(32, element.name.text); + return getLiteralType(element.name.text); case 144: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512)) { @@ -33585,7 +34195,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183; var isDecorator = node.kind === 147; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -33613,7 +34223,7 @@ var ts; var candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -33654,25 +34264,56 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -33682,14 +34323,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -33820,7 +34453,7 @@ var ts; } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } if (isTypeAny(expressionType)) { @@ -33947,8 +34580,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -34092,7 +34725,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048); + return getNullableType(type, 2048); } } return type; @@ -34156,10 +34789,10 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 || - parameter.valueDeclaration.name.kind === 175)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -34443,15 +35076,15 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { error(operand, diagnostic); return false; } return true; } function isReadonlySymbol(symbol) { - return !!(getCheckFlags(symbol) & 8 || - symbol.flags & 4 && getDeclarationModifierFlagsFromSymbol(symbol) & 64 || + return !!(ts.getCheckFlags(symbol) & 8 || + symbol.flags & 4 && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 || symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || symbol.flags & 98304 && !(symbol.flags & 65536) || symbol.flags & 8); @@ -34531,7 +35164,7 @@ var ts; return silentNeverType; } if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37: @@ -34574,8 +35207,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -34589,8 +35222,8 @@ var ts; } if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -34599,8 +35232,8 @@ var ts; } if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -34635,7 +35268,7 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 | 512))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { @@ -34907,7 +35540,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { + if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { resultType = numberType; } else { @@ -34961,7 +35594,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53: return getTypeFacts(leftType) & 1048576 ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54: return getTypeFacts(leftType) & 2097152 ? @@ -35043,12 +35676,12 @@ var ts; var func = ts.getContainingFunction(node); var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 4096); - } + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256); } } @@ -35088,9 +35721,9 @@ var ts; } switch (node.kind) { case 9: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: return trueType; case 86: @@ -35144,7 +35777,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 | 262144)); + return maybeTypeOfKind(contextualType, (224 | 262144)); } return false; } @@ -35441,17 +36074,14 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - if (languageVersion < 2) { - checkExternalEmitHelpers(node, 128); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); } - } - if ((functionFlags & 5) === 1) { - if (functionFlags & 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 2048); + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); } - else if (languageVersion < 2) { + if ((functionFlags & 3) !== 0 && languageVersion < 2) { checkExternalEmitHelpers(node, 128); } } @@ -35474,7 +36104,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5) === 1) { + if ((functionFlags_1 & (4 | 1)) === 1) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -35595,7 +36225,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -35669,7 +36299,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -35807,7 +36438,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { + if (type.flags & 16 && getNodeLinks(node).resolvedSymbol.flags & 8) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -35846,7 +36477,7 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 340)) { + if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1)) { return type; @@ -35896,16 +36527,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 | 16)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -35916,7 +36547,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -36024,7 +36655,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && @@ -36037,8 +36668,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -36087,11 +36718,12 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -36287,7 +36919,9 @@ var ts; checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 ? 793064 : 1920) | 8388608, undefined, undefined); if (rootSymbol @@ -36297,6 +36931,43 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167: + case 166: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + return undefined; + } + if (commonEntityName) { + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168: + return getEntityNameForDecoratorMetadata(node.type); + case 159: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -36323,7 +36994,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -36332,15 +37003,15 @@ var ts; case 154: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -36453,15 +37124,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -36539,7 +37211,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -36601,7 +37273,7 @@ var ts; if (getNodeCheckFlags(current) & 4) { var isDeclaration_1 = node.kind !== 71; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -36615,7 +37287,7 @@ var ts; if (getNodeCheckFlags(current) & 8) { var isDeclaration_2 = node.kind !== 71; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -36811,7 +37483,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -36917,11 +37589,12 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216) { if (node.awaitModifier) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 8192); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); } } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } } @@ -37371,11 +38044,14 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -37590,7 +38266,7 @@ var ts; } } function getTargetSymbol(s) { - return getCheckFlags(s) & 1 ? s.target : s; + return ts.getCheckFlags(s) & 1 ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -37609,7 +38285,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { @@ -37624,13 +38300,10 @@ var ts; } } else { - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { continue; } - if ((baseDeclarationFlags & 32) !== (derivedDeclarationFlags & 32)) { - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { continue; } @@ -37649,7 +38322,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -37732,88 +38405,81 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); + nodeLinks.flags |= 16384; var autoValue = 0; - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37: return value_1; case 38: return -value_1; case 52: return ~value_1; } - return undefined; - case 194: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49: return left | right; case 48: return left & right; case 46: return left >> right; @@ -37826,75 +38492,53 @@ var ts; case 38: return left - right; case 42: return left % right; } - return undefined; - case 8: - checkGrammarNumericLiteral(e); - return +e.text; - case 185: - return evalConstant(e.expression); - case 71: - case 180: - case 179: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71) { - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9: + return expr.text; + case 8: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185: + return evaluate(expr.expression); + case 71: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180: + case 179: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384) { + var name = expr.kind === 179 ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - var current = expression; - while (current) { - if (current.kind === 71) { - break; - } - else if (current.kind === 179) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - if (member === propertyDecl) { - return undefined; - } - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return 0; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 || + node.kind === 179 && isConstantMemberAccess(node.expression) || + node.kind === 180 && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -37917,7 +38561,7 @@ var ts; if (enumSymbol.declarations.length > 1) { ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -38142,6 +38786,9 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + if (node.kind === 246 && compilerOptions.isolatedModules && !(target.flags & 107455)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -38788,7 +39435,7 @@ var ts; if (isInsideWithStatementBody(node)) { return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { return getSymbolOfNode(node.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { @@ -38901,7 +39548,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -38963,16 +39610,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728) { if (symbol.leftSpread) { @@ -39233,7 +39880,7 @@ var ts; else if (isTypeOfKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340)) { + else if (isTypeOfKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178)) { @@ -39261,7 +39908,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -39273,15 +39920,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -39360,7 +39998,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -39507,7 +40144,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 8192; helper <<= 1) { + for (var helper = 1; helper <= 16384; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); @@ -39534,9 +40171,10 @@ var ts; case 256: return "__values"; case 512: return "__read"; case 1024: return "__spread"; - case 2048: return "__asyncGenerator"; - case 4096: return "__asyncDelegator"; - case 8192: return "__asyncValues"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -40565,6 +41203,17 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242: + case 246: + if (name.parent.propertyName) { + return true; + } + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -40675,49 +41324,59 @@ var ts; if ((kind > 0 && kind <= 142) || kind === 169) { return node; } - switch (node.kind) { - case 206: - case 209: - case 200: - case 225: - case 298: - case 247: - return node; + switch (kind) { + case 71: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - case 160: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 145: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); - case 159: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 148: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 158: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170: @@ -40728,20 +41387,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - case 145: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 148: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 174: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 175: @@ -40778,12 +41423,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196: @@ -40800,6 +41445,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); case 205: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 207: @@ -40844,6 +41491,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233: @@ -40852,6 +41503,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238: @@ -40876,8 +41529,6 @@ var ts; return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 249: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251: @@ -40886,6 +41537,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256: @@ -40910,6 +41563,8 @@ var ts; return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); case 296: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; } @@ -40965,6 +41620,13 @@ var ts; case 147: result = reduceNode(node.expression, cbNode, result); break; + case 148: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -41303,6 +41965,9 @@ var ts; case 296: result = reduceNode(node.expression, cbNode, result); break; + case 297: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -41753,7 +42418,7 @@ var ts; var applicableSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -42542,15 +43207,10 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || serializedUnion.text !== serializedIndividual.text) { @@ -42837,7 +43497,12 @@ var ts; } function transformEnumMember(member) { var name = getExpressionForPropertyName(member, false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } function transformEnumMemberDeclarationValue(member) { var value = resolver.getConstantValue(member); @@ -42884,9 +43549,9 @@ var ts; return false; } function addVarForEnumOrModuleDeclaration(statements, node) { - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, false, true)) - ]); + ], currentScope.kind === 265 ? 0 : 1)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -43019,7 +43684,7 @@ var ts; } function visitExportDeclaration(node) { if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { return undefined; @@ -43329,7 +43994,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -43574,7 +44239,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -43642,19 +44307,14 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), node), node); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -43781,6 +44441,9 @@ var ts; } return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); } + function awaitAsYield(expression) { + return ts.createYield(undefined, enclosingFunctionFlags & 1 ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); @@ -43788,19 +44451,17 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(undefined); - var values = createAsyncValuesHelper(context, expression, node.expression); - var next = ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), - ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), node), 256); + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, awaitAsYield(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -43809,12 +44470,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -44046,12 +44702,22 @@ var ts; return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ @@ -44063,11 +44729,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); } var asyncValues = { @@ -44086,7 +44752,7 @@ var ts; var compilerOptions = context.getCompilerOptions(); return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -44524,7 +45190,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -44666,7 +45332,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -45529,12 +46195,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { updated = undefined; @@ -46422,7 +47089,7 @@ var ts; if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -46590,8 +47257,7 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; } currentSourceFile = node; @@ -48277,7 +48943,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -48440,9 +49106,9 @@ var ts; return visitFunctionDeclaration(node); case 229: return visitClassDeclaration(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return node; @@ -48946,9 +49612,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -49461,9 +50125,9 @@ var ts; return visitCatchClause(node); case 207: return visitBlock(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -49754,7 +50418,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -49869,7 +50533,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299); + var enabledSyntaxKindFeatures = new Array(300); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -49927,7 +50591,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } function enableSubstitution(kind) { ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); @@ -50097,7 +50761,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencesOutput = ""; @@ -50122,11 +50786,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -50530,8 +51194,7 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -50544,23 +51207,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -50570,12 +51240,6 @@ var ts; var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -50645,7 +51309,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && !noDeclare) { + else if (node.kind !== 230 && needsDeclare) { write("declare "); } } @@ -50873,7 +51537,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -50970,7 +51634,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -50982,12 +51646,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 229) { @@ -51001,7 +51659,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -51016,6 +51674,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128)) { @@ -51023,15 +51694,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); write(" {"); writeLine(); increaseIndent(); @@ -51052,7 +51730,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, false); + emitHeritageClause(interfaceExtendsTypes, false); } write(" {"); writeLine(); @@ -51104,7 +51782,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 || node.kind === 148) { + else if (node.kind === 149 || node.kind === 148 || + (node.kind === 146 && ts.hasModifier(node.parent, 8))) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -51112,7 +51791,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 229 || node.kind === 146) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -51307,6 +51986,11 @@ var ts; write("["); } else { + if (node.kind === 152 && ts.hasModifier(node, 8)) { + write("();"); + writeLine(); + return; + } if (node.kind === 156 || node.kind === 161) { write("new "); } @@ -51565,7 +52249,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { declFileName = referencedFile.fileName; } else { @@ -52328,7 +53012,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -52359,7 +53043,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -52445,7 +53129,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -52521,7 +53207,7 @@ var ts; function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -52721,7 +53407,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -52741,7 +53427,7 @@ var ts; case 97: case 101: case 99: - writeTokenText(kind); + writeTokenNode(node); return; case 177: return emitArrayLiteralExpression(node); @@ -52803,6 +53489,8 @@ var ts; return emitJsxSelfClosingElement(node); case 296: return emitPartiallyEmittedExpression(node); + case 297: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -52828,6 +53516,7 @@ var ts; } function emitIdentifier(node) { write(getTextOfNode(node, false)); + emitTypeArguments(node, node.typeArguments); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -52850,6 +53539,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -52964,7 +53654,9 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65); + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 ? 448 : 65); + } write("}"); } function emitArrayType(node) { @@ -53002,9 +53694,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -53015,8 +53713,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -53029,7 +53732,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432); + emitList(node, elements, ts.getEmitFlags(node) & 1 ? 272 : 432); write("}"); } } @@ -53105,7 +53808,7 @@ var ts; } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -53196,7 +53899,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -53875,6 +54578,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272); + } function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { for (var i = 0; i < statements.length; i++) { var statement = statements[i]; @@ -54123,6 +54829,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -54300,7 +55015,9 @@ var ts; if (node.kind === 9 && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -54514,14 +55231,17 @@ var ts; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; @@ -54735,6 +55455,83 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); + lineContent = lineContent.replace("\t", " "); + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -54784,6 +55581,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -54826,7 +55624,8 @@ var ts; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); if (typeReferences.length) { @@ -54875,7 +55674,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -54908,45 +55708,64 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { + if (structuralIsReused === 0 && !file.ambientModuleNames.length) { return resolveModuleNamesWorker(moduleNames, containingFile); } + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } var unknownModuleNames; var result; var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - var isKnownToResolveToAmbientModule = false; + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - result = new Array(moduleNames.length); - unknownModuleNames = moduleNames.slice(0, i); - } - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - unknownModuleNames.push(moduleName); + else { + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; + if (!result) { + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -54955,15 +55774,12 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -54982,67 +55798,73 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0; } var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 | 1))); var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0; } var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - newSourceFile = oldSourceFile; - } newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -55050,11 +55872,16 @@ var ts; var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; } for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); @@ -55066,8 +55893,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { return { @@ -55407,7 +56233,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -55438,7 +56264,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -55479,13 +56304,13 @@ var ts; } break; case 233: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { (ambientModules || (ambientModules = [])).push(moduleName.text); } var body = node.body; @@ -55508,45 +56333,50 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -55682,10 +56512,10 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -55734,7 +56564,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -55831,12 +56661,12 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -56068,6 +56898,7 @@ var ts; "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -56919,49 +57750,28 @@ var ts; if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + if (exclude) { + json.exclude = exclude; } - if (include && !json["include"]) { - json["include"] = include; + if (files) { + json.files = files; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } + return options; + })(); options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -56971,37 +57781,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -57032,9 +57812,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; @@ -57051,9 +57828,66 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -57509,7 +58343,6 @@ var ts; case 148: case 261: case 262: - case 264: case 151: case 150: case 152: @@ -57526,9 +58359,11 @@ var ts; case 231: case 163: return 2; + case 264: case 229: - case 232: return 1 | 2; + case 232: + return 7; case 233: if (ts.isAmbientModule(node)) { return 4 | 1; @@ -57545,7 +58380,7 @@ var ts; case 238: case 243: case 244: - return 1 | 2 | 4; + return 7; case 265: return 4 | 1; } @@ -57700,7 +58535,7 @@ var ts; case 153: case 154: case 233: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180: return node.parent.argumentExpression === node; case 144: @@ -57715,31 +58550,6 @@ var ts; ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; - function isInsideComment(sourceFile, token, position) { - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47) { - return true; - } - else { - return !(text.charCodeAt(comment.end - 1) === 47 && - text.charCodeAt(comment.end - 2) === 42); - } - } - return false; - }); - } - } - ts.isInsideComment = isInsideComment; function getContainerNode(node) { while (true) { node = node.parent; @@ -58045,43 +58855,24 @@ var ts; if (ts.isToken(current)) { return current; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } - for (var _a = 0, _b = current.getChildren(); _a < _b.length; _a++) { - var child = _b[_a]; - if (ts.isJSDocNode(child)) { + for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + if (ts.isJSDocNode(child) && !includeJsDocComment) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + continue; + } + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } @@ -58175,10 +58966,6 @@ var ts; return false; } ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, undefined); - } - ts.isInComment = isInComment; function isInsideJsxElementOrAttribute(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); if (!token) { @@ -58207,20 +58994,29 @@ var ts; return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 ? position <= c.end : position < c.end); }); + function isInComment(sourceFile, position, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position); } + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); + function isInCommentRange(commentRanges) { + return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); + } + } + ts.isInComment = isInComment; + function isPositionInCommentRange(_a, position, text) { + var pos = _a.pos, end = _a.end, kind = _a.kind; + if (pos < position && position < end) { + return true; + } + else if (position === end) { + return kind === 2 || + !(text.charCodeAt(end - 1) === 47 && text.charCodeAt(end - 2) === 42); + } + else { + return false; } - return false; } - ts.isInCommentHelper = isInCommentHelper; function hasDocComment(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); @@ -58336,6 +59132,9 @@ var ts; } ts.isAccessibilityModifier = isAccessibilityModifier; function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } for (var e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { @@ -58376,25 +59175,27 @@ var ts; } ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { + return isInComment(sourceFile, position, undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { + return isInComment(sourceFile, position, undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInNonReferenceComment = isInNonReferenceComment; function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; function isTypeKeyword(kind) { switch (kind) { case 119: @@ -58654,8 +59455,8 @@ var ts; }; var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; diagnostic.start = diagnostic.start - 1; } var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; @@ -59202,7 +60003,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -59210,8 +60011,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -60070,8 +60871,8 @@ var ts; continue; } var start = completePrefix.length; - var length_6 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_6))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -60328,7 +61129,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; if (requestJsDocTagName) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; } @@ -60352,13 +61153,16 @@ var ts; sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); } - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + if (hasFilteredClassMemberKeywords) { + ts.addRange(entries, classMemberKeywordCompletions); + } + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; @@ -60403,8 +61207,8 @@ var ts; var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { + var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -60461,10 +61265,11 @@ var ts; function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) { var candidates = []; var entries = []; + var uniques = ts.createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { var candidate = candidates_3[_i]; - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; @@ -60492,9 +61297,10 @@ var ts; } return undefined; } - function addStringLiteralCompletionsFromType(type, result, typeChecker) { + function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 16384) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; @@ -60502,16 +61308,20 @@ var ts; if (type.flags & 65536) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & 32) { - result.push({ - name: type.text, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, - sortText: "0" - }); + var name = type.value; + if (!uniques.has(name)) { + uniques.set(name, true); + result.push({ + name: name, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } } } function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { @@ -60562,7 +61372,7 @@ var ts; var currentToken = ts.getTokenAtPosition(sourceFile, position); log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); - var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { @@ -60592,7 +61402,7 @@ var ts; } } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -60663,6 +61473,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; + var hasFilteredClassMemberKeywords = false; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -60693,7 +61504,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols() { isGlobalCompletion = false; isMemberCompletion = true; @@ -60735,6 +61546,7 @@ var ts; function tryGetGlobalSymbols() { var objectLikeContainer; var namedImportsOrExports; + var classLikeContainer; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); @@ -60742,6 +61554,10 @@ var ts; if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; + } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; if ((jsxContainer.kind === 250) || (jsxContainer.kind === 251)) { @@ -60871,12 +61687,14 @@ var ts; } function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { isMemberCompletion = true; - var typeForObject; + var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178) { isNewIdentifierLocation = true; - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 174) { @@ -60893,7 +61711,10 @@ var ts; } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = objectLikeContainer.elements; } } @@ -60904,10 +61725,6 @@ var ts; else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { symbols = filterObjectMembersList(typeMembers, existingMembers); } @@ -60933,6 +61750,42 @@ var ts; symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); return true; } + function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + isMemberCompletion = true; + isNewIdentifierLocation = true; + hasFilteredClassMemberKeywords = true; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); + var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + if (contextToken.kind === 71 && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32; + break; + } + } + if (!(classElementModifierFlags & 8)) { + var baseClassTypeToGetPropertiesFrom = void 0; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & 32) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32) ? + undefined : + ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + } + } + } function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { @@ -60961,6 +61814,37 @@ var ts; } return undefined; } + function isFromClassElementDeclaration(node) { + return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); + } + function tryGetClassLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 17: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + case 26: + case 25: + case 18: + if (ts.isClassLike(location)) { + return location; + } + break; + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent; + } + } + } + if (location && location.kind === 294 && ts.isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -61050,7 +61934,7 @@ var ts; containingNodeKind === 231 || isFunction(containingNodeKind); case 115: - return containingNodeKind === 149; + return containingNodeKind === 149 && !ts.isClassLike(contextToken.parent.parent); case 24: return containingNodeKind === 146 || (contextToken.parent && contextToken.parent.parent && @@ -61063,13 +61947,16 @@ var ts; return containingNodeKind === 242 || containingNodeKind === 246 || containingNodeKind === 240; + case 125: + case 135: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } case 75: case 83: case 109: case 89: case 104: - case 125: - case 135: case 91: case 110: case 76: @@ -61077,6 +61964,10 @@ var ts; case 138: return true; } + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } switch (contextToken.getText()) { case "abstract": case "async": @@ -61108,7 +61999,7 @@ var ts; var existingImportsOrExports = ts.createMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; @@ -61134,7 +62025,7 @@ var ts; m.kind !== 154) { continue; } - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; @@ -61144,17 +62035,51 @@ var ts; } } else { - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); } + function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + if (m.kind !== 149 && + m.kind !== 151 && + m.kind !== 153 && + m.kind !== 154) { + continue; + } + if (isCurrentlyEditingNode(m)) { + continue; + } + if (ts.hasModifier(m, 8)) { + continue; + } + var mIsStatic = ts.hasModifier(m, 32); + var currentElementIsStatic = !!(currentClassElementModifierFlags & 32); + if ((mIsStatic && !currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return ts.concatenate(ts.filter(baseSymbols, function (baseProperty) { return isValidProperty(baseProperty, 8); }), ts.filter(implementingTypeSymbols, function (implementingProperty) { return isValidProperty(implementingProperty, 24); })); + function isValidProperty(propertySymbol, inValidModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } + } function filterJsxAttributes(symbols, attributes) { var seenNames = ts.createMap(); for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253) { @@ -61163,6 +62088,9 @@ var ts; } return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); } + function isCurrentlyEditingNode(node) { + return node.getStart() <= position && position <= node.getEnd(); + } } function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { var displayName = ts.getDeclaredName(typeChecker, symbol, location); @@ -61198,6 +62126,27 @@ var ts; sortText: "0" }); } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 114: + case 113: + case 112: + case 117: + case 115: + case 123: + case 131: + case 125: + case 135: + case 120: + return true; + } + } + function isClassMemberCompletionKeywordText(text) { + return isClassMemberCompletionKeyword(ts.stringToToken(text)); + } + var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { + return isClassMemberCompletionKeywordText(entry.name); + }); function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -61213,9 +62162,9 @@ var ts; (function (ts) { var DocumentHighlights; (function (DocumentHighlights) { - function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) { + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -61227,8 +62176,8 @@ var ts; kind: ts.HighlightSpanKind.none }; } - function getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -61954,6 +62903,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240) { @@ -62019,10 +62971,41 @@ var ts; } }); } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 265) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -62044,7 +63027,7 @@ var ts; }); } function forEachImport(sourceFile, action) { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); @@ -62072,25 +63055,20 @@ var ts; } } }); - if (sourceFile.flags & 65536) { - sourceFile.forEachChild(function recur(node) { - if (ts.isRequireCall(node, true)) { - action(node, node.arguments[0]); - } - else { - node.forEachChild(recur); - } - }); - } } } function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; - if (decl.kind === 238 || decl.kind === 244) { - return decl; + switch (decl.kind) { + case 181: + case 238: + case 244: + return decl; + case 248: + return decl.parent; + default: + ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); } - ts.Debug.assert(decl.kind === 248); - return decl.parent; } function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { return comingFromExport ? getExport() : getExport() || getImport(); @@ -62209,12 +63187,13 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + return ts.forEach(symbol.declarations, function (decl) { + if (ts.isExportAssignment(decl)) { + return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + } + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 && name.text; }); - ts.Debug.assert(!!name); - return name; } function skipExportSpecifierSymbol(symbol, checker) { if (symbol.declarations) @@ -62257,12 +63236,13 @@ var ts; return { type: "node", node: node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; - function findReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } var out = []; + var checker = program.getTypeChecker(); for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; if (definition) { @@ -62272,39 +63252,41 @@ var ts; return out; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; - function getImplementationsAtPosition(checker, cancellationToken, sourceFiles, sourceFile, position) { + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(typeChecker, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + var checker = program.getTypeChecker(); if (node.parent.kind === 262) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 || ts.isSuperProperty(node.parent)) { - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(checker, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { + var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options) { + function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -62314,10 +63296,6 @@ var ts; switch (def.type) { case "symbol": { var symbol = def.symbol, node_2 = def.node; - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; @@ -62454,7 +63432,7 @@ var ts; (function (FindAllReferences) { var Core; (function (Core) { - function getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } if (node.kind === 265) { return undefined; @@ -62465,6 +63443,7 @@ var ts; return special; } } + var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); if (!symbol) { if (!options.implementations && node.kind === 9) { @@ -62472,12 +63451,59 @@ var ts; } return undefined; } - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; + if (symbol.flags & 1536 && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleReferenceLocation(node) { + if (node.kind !== 9) { + return false; + } + switch (node.parent.kind) { + case 233: + case 248: + case 238: + case 244: + return true; + case 181: + return ts.isRequireCall(node.parent, false); + default: + return false; + } + } + function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 265: + break; + case 233: + references.push({ type: "node", node: decl.name }); + break; + default: + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + return [{ + definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, + references: references + }]; + } function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken); @@ -62672,7 +63698,11 @@ var ts; } return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + if (container === void 0) { container = sourceFile; } + if (fullStart === void 0) { fullStart = false; } + var start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + var end = container.getEnd(); var positions = []; if (!symbolName || !symbolName.length) { return positions; @@ -62697,15 +63727,11 @@ var ts; var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { var position = possiblePositions_1[_i]; var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } - if (node === targetLabel || - (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } } @@ -62714,27 +63740,27 @@ var ts; function isValidReferencePosition(node, searchSymbolName) { switch (node && node.kind) { case 71: - return node.getWidth() === searchSymbolName.length; + return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; case 9: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - node.getWidth() === searchSymbolName.length + 2; + node.text.length === searchSymbolName.length; case 8: - return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; default: return false; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); @@ -62751,10 +63777,8 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - var start = state.findInComments ? container.getFullStart() : container.getStart(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, state.findInComments); _i < _a.length; _i++) { + var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } @@ -62862,7 +63886,7 @@ var ts; var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); if (!(flags & 134217728) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -63092,9 +64116,9 @@ var ts; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { - var position = possiblePositions_4[_i]; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); + for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { + var position = possiblePositions_3[_i]; var node = ts.getTouchingWord(sourceFile, position); if (!node || node.kind !== 97) { continue; @@ -63138,13 +64162,13 @@ var ts; if (searchSpaceNode.kind === 265) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ @@ -63188,10 +64212,10 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } return [{ @@ -63199,8 +64223,8 @@ var ts; references: references }]; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { - for (var _i = 0, possiblePositions_5 = possiblePositions; _i < possiblePositions_5.length; _i++) { - var position = possiblePositions_5[_i]; + for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { + var position = possiblePositions_4[_i]; var node_7 = ts.getTouchingWord(sourceFile, position); if (node_7 && node_7.kind === 9 && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, true)); @@ -63329,20 +64353,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_5 = []; + var result_6 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -63481,12 +64505,10 @@ var ts; if (!symbol) { return undefined; } - if (symbol.flags & 8388608) { - var declaration = symbol.declarations[0]; - if (node.kind === 71 && - (node.parent === declaration || - (declaration.kind === 242 && declaration.parent && declaration.parent.kind === 241))) { - symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.flags & 8388608 && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; } } if (node.parent.kind === 262) { @@ -63500,21 +64522,11 @@ var ts; var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } - if (ts.isJsxOpeningLikeElement(node.parent)) { - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } var element = ts.getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent)) { - var result = []; - var propertySymbols = ts.getPropertySymbolsFromContextualType(typeChecker, element); - for (var _i = 0, propertySymbols_1 = propertySymbols; _i < propertySymbols_1.length; _i++) { - var propertySymbol = propertySymbols_1[_i]; - result.push.apply(result, getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent)) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); } return getDefinitionFromSymbol(typeChecker, symbol, node); } @@ -63533,13 +64545,13 @@ var ts; return undefined; } if (type.flags & 65536 && !(type.flags & 16)) { - var result_6 = []; + var result_7 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_6, getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(result_7, getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_6; + return result_7; } if (!type.symbol) { return undefined; @@ -63547,6 +64559,23 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function shouldSkipAlias(node, declaration) { + if (node.kind !== 71) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 239: + case 237: + return true; + case 242: + return declaration.parent.kind === 241; + default: + return false; + } + } function getDefinitionFromSymbol(typeChecker, symbol, node) { var result = []; var declarations = symbol.getDeclarations(); @@ -63611,7 +64640,7 @@ var ts; } } function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { var sourceFile = name.getSourceFile(); @@ -63638,7 +64667,7 @@ var ts; function findReferenceInPosition(refs, pos) { for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } @@ -63707,6 +64736,7 @@ var ts; "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -63717,8 +64747,6 @@ var ts; "throws", "type", "typedef", - "property", - "prop", "version" ]; var jsDocTagNameCompletionEntries; @@ -64092,8 +65120,8 @@ var ts; } }); }; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_4(sourceFile); } rawItems = ts.filter(rawItems, function (item) { @@ -64134,16 +65162,19 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144) { - return tryAddComputedPropertyName(declaration.name.expression, containers, true); - } - else { - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144) { + return tryAddComputedPropertyName(name.expression, containers, true); + } + else { + return false; + } } } return true; @@ -64167,8 +65198,9 @@ var ts; } function getContainers(declaration) { var containers = []; - if (declaration.name.kind === 144) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144) { + if (!tryAddComputedPropertyName(name.expression, containers, false)) { return undefined; } } @@ -64201,6 +65233,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -64209,8 +65242,8 @@ var ts; isCaseSensitive: rawItem.isCaseSensitive, fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -64424,8 +65457,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { return true; } @@ -64503,9 +65536,9 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186: @@ -64522,7 +65555,7 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -65742,7 +66775,7 @@ var ts; } } function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (node.parent.kind === 181 || node.parent.kind === 182) { + if (ts.isCallOrNewExpression(node.parent)) { var callExpression = node.parent; if (node.kind === 27 || node.kind === 19) { @@ -66120,7 +67153,7 @@ var ts; } } var callExpressionLike = void 0; - if (location.kind === 181 || location.kind === 182) { + if (ts.isCallOrNewExpression(location)) { callExpressionLike = location; } else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { @@ -66185,24 +67218,29 @@ var ts; } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || (location.kind === 123 && location.parent.kind === 152)) { - var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); - if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); + var functionDeclaration_1 = location.parent; + var locationIsSymbolDeclaration = ts.findDeclaration(symbol, function (declaration) { + return declaration === (location.kind === 123 ? functionDeclaration_1.parent : functionDeclaration_1); + }); + if (locationIsSymbolDeclaration) { + var allSignatures = functionDeclaration_1.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration_1.kind === 152) { + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 && + !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; } - else { - signature = allSignatures[0]; - } - if (functionDeclaration.kind === 152) { - symbolKind = ts.ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 155 && - !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; } } } @@ -66266,9 +67304,9 @@ var ts; writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - var declaration = ts.getDeclarationOfKind(symbol, 145); - ts.Debug.assert(declaration !== undefined); - declaration = declaration.parent; + var decl = ts.getDeclarationOfKind(symbol, 145); + ts.Debug.assert(decl !== undefined); + var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); @@ -66302,7 +67340,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58)); displayParts.push(ts.spacePart()); - displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); } } } @@ -66548,7 +67586,7 @@ var ts; ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); ts.addRange(diagnostics, program.getOptionsDiagnostics()); } - program.emit(); + program.emit(undefined, undefined, undefined, undefined, transpileOptions.transformers); ts.Debug.assert(outputText !== undefined, "Output generation failed"); return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } @@ -66822,9 +67860,10 @@ var ts; var formatting; (function (formatting) { var FormattingContext = (function () { - function FormattingContext(sourceFile, formattingRequestKind) { + function FormattingContext(sourceFile, formattingRequestKind, options) { this.sourceFile = sourceFile; this.formattingRequestKind = formattingRequestKind; + this.options = options; } FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); @@ -67062,7 +68101,7 @@ var ts; this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.FromTokens([22, 26, 25])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyExcept(120), 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(22, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); @@ -67070,10 +68109,10 @@ var ts; this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([20, 3, 81, 102, 87, 82]); this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); + this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); @@ -67090,11 +68129,12 @@ var ts; this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(38, 44), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 26), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([104, 100, 94, 80, 96, 103, 121]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterNewKeywordOnConstructorSignature = new formatting.Rule(formatting.RuleDescriptor.create1(94, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConstructorSignatureContext), 8)); this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([110, 76]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(89, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); + this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(105, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(96, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([20, 81, 82, 73]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); @@ -67102,8 +68142,8 @@ var ts; this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125, 135]), 71), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([128, 132]), 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([117, 75, 124, 79, 83, 84, 85, 125, 108, 91, 109, 128, 129, 112, 114, 113, 131, 135, 115, 138, 140, 127]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([85, 108, 140])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); @@ -67134,6 +68174,41 @@ var ts; this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 58), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(58, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBeforeNonNullAssertionOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 51), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonNullAssertionContext), 8)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); + this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 2)); + this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 8)); + this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 2)); + this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 8)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, @@ -67177,7 +68252,25 @@ var ts; this.SpaceBeforeAt, this.NoSpaceAfterAt, this.SpaceAfterDecorator, - this.NoSpaceBeforeNonNullAssertionOperator + this.NoSpaceBeforeNonNullAssertionOperator, + this.NoSpaceAfterNewKeywordOnConstructorSignature + ]; + this.UserConfigurableRules = [ + this.SpaceAfterConstructor, this.NoSpaceAfterConstructor, + this.SpaceAfterComma, this.NoSpaceAfterComma, + this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, + this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, + this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, + this.SpaceAfterOpenBracket, this.SpaceBeforeCloseBracket, this.NoSpaceBetweenBrackets, this.NoSpaceAfterOpenBracket, this.NoSpaceBeforeCloseBracket, + this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceAfterOpenBrace, this.NoSpaceBeforeCloseBrace, + this.SpaceAfterTemplateHeadAndMiddle, this.SpaceBeforeTemplateMiddleAndTail, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, + this.SpaceAfterOpenBraceInJsxExpression, this.SpaceBeforeCloseBraceInJsxExpression, this.NoSpaceAfterOpenBraceInJsxExpression, this.NoSpaceBeforeCloseBraceInJsxExpression, + this.SpaceAfterSemicolonInFor, this.NoSpaceAfterSemicolonInFor, + this.SpaceBeforeBinaryOperator, this.SpaceAfterBinaryOperator, this.NoSpaceBeforeBinaryOperator, this.NoSpaceAfterBinaryOperator, + this.SpaceBeforeOpenParenInFuncDecl, this.NoSpaceBeforeOpenParenInFuncDecl, + this.NewLineBeforeOpenBraceInControl, + this.NewLineBeforeOpenBraceInFunction, this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock, + this.SpaceAfterTypeAssertion, this.NoSpaceAfterTypeAssertion ]; this.LowPriorityCommonRules = [ this.NoSpaceBeforeSemicolon, @@ -67188,41 +68281,6 @@ var ts; this.SpaceAfterSemicolon, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); - this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8)); - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); } Rules.prototype.getRuleName = function (rule) { var o = this; @@ -67233,6 +68291,18 @@ var ts; } throw new Error("Unknown rule"); }; + Rules.IsOptionEnabled = function (optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + }; + Rules.IsOptionDisabled = function (optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + }; + Rules.IsOptionDisabledOrUndefined = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + }; + Rules.IsOptionEnabledOrUndefined = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + }; Rules.IsForContext = function (context) { return context.contextNode.kind === 214; }; @@ -67448,6 +68518,9 @@ var ts; Rules.IsObjectTypeContext = function (context) { return context.contextNode.kind === 163; }; + Rules.IsConstructorSignatureContext = function (context) { + return context.contextNode.kind === 156; + }; Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { if (token.kind !== 27 && token.kind !== 29) { return false; @@ -67529,8 +68602,7 @@ var ts; }; RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { var _this = this; - var specificRule = rule.Descriptor.LeftTokenRange !== formatting.Shared.TokenRange.Any && - rule.Descriptor.RightTokenRange !== formatting.Shared.TokenRange.Any; + var specificRule = rule.Descriptor.LeftTokenRange.isSpecific() && rule.Descriptor.RightTokenRange.isSpecific(); rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); @@ -67638,27 +68710,14 @@ var ts; (function (formatting) { var Shared; (function (Shared) { - var TokenRangeAccess = (function () { - function TokenRangeAccess(from, to, except) { - this.tokens = []; - for (var token = from; token <= to; token++) { - if (ts.indexOf(except, token) < 0) { - this.tokens.push(token); - } - } - } - TokenRangeAccess.prototype.GetTokens = function () { - return this.tokens; - }; - TokenRangeAccess.prototype.Contains = function (token) { - return this.tokens.indexOf(token) >= 0; - }; - return TokenRangeAccess; - }()); - Shared.TokenRangeAccess = TokenRangeAccess; + var allTokens = []; + for (var token = 0; token <= 142; token++) { + allTokens.push(token); + } var TokenValuesAccess = (function () { - function TokenValuesAccess(tks) { - this.tokens = tks && tks.length ? tks : []; + function TokenValuesAccess(tokens) { + if (tokens === void 0) { tokens = []; } + this.tokens = tokens; } TokenValuesAccess.prototype.GetTokens = function () { return this.tokens; @@ -67666,9 +68725,9 @@ var ts; TokenValuesAccess.prototype.Contains = function (token) { return this.tokens.indexOf(token) >= 0; }; + TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { this.token = token; @@ -67679,18 +68738,14 @@ var ts; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { return tokenValue === this.token; }; + TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { - var result = []; - for (var token = 0; token <= 142; token++) { - result.push(token); - } - return result; + return allTokens; }; TokenAllAccess.prototype.Contains = function () { return true; @@ -67698,51 +68753,80 @@ var ts; TokenAllAccess.prototype.toString = function () { return "[allTokens]"; }; + TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - Shared.TokenAllAccess = TokenAllAccess; - var TokenRange = (function () { - function TokenRange(tokenAccess) { - this.tokenAccess = tokenAccess; + var TokenAllExceptAccess = (function () { + function TokenAllExceptAccess(except) { + this.except = except; } - TokenRange.FromToken = function (token) { - return new TokenRange(new TokenSingleValueAccess(token)); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - TokenRange.FromRange = function (f, to, except) { - if (except === void 0) { except = []; } - return new TokenRange(new TokenRangeAccess(f, to, except)); - }; - TokenRange.AllTokens = function () { - return new TokenRange(new TokenAllAccess()); - }; - TokenRange.prototype.GetTokens = function () { - return this.tokenAccess.GetTokens(); - }; - TokenRange.prototype.Contains = function (token) { - return this.tokenAccess.Contains(token); - }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); - }; - return TokenRange; + TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; + return TokenAllExceptAccess; }()); - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); - TokenRange.Keywords = TokenRange.FromRange(72, 142); - TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([92, 93, 142, 118, 126]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([43, 44, 52, 51]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 71, 19, 21, 17, 99, 94]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([71, 19, 99, 94]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([71, 20, 22, 94]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([71, 19, 99, 94]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([71, 20, 22, 94]); - TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([71, 133, 136, 122, 137, 105, 119]); - Shared.TokenRange = TokenRange; + var TokenRange; + (function (TokenRange) { + function FromToken(token) { + return new TokenSingleValueAccess(token); + } + TokenRange.FromToken = FromToken; + function FromTokens(tokens) { + return new TokenValuesAccess(tokens); + } + TokenRange.FromTokens = FromTokens; + function FromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); + } + TokenRange.FromRange = FromRange; + function AnyExcept(token) { + return new TokenAllExceptAccess(token); + } + TokenRange.AnyExcept = AnyExcept; + TokenRange.Any = new TokenAllAccess(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3])); + TokenRange.Keywords = TokenRange.FromRange(72, 142); + TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ + 92, 93, 142, 118, 126 + ]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ + 43, 44, 52, 51 + ]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ + 8, 71, 19, 21, + 17, 99, 94 + ]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ + 71, 19, 99, 94 + ]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ + 71, 20, 22, 94 + ]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ + 71, 19, 99, 94 + ]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ + 71, 20, 22, 94 + ]); + TokenRange.Comments = TokenRange.FromTokens([2, 3]); + TokenRange.TypeNames = TokenRange.FromTokens([ + 71, 133, 136, 122, + 137, 105, 119 + ]); + })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -67753,6 +68837,8 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); + var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + this.rulesMap = formatting.RulesMap.create(activeRules); } RulesProvider.prototype.getRuleName = function (rule) { return this.globalRules.getRuleName(rule); @@ -67768,121 +68854,9 @@ var ts; }; RulesProvider.prototype.ensureUpToDate = function (options) { if (!this.options || !ts.compareDataObjects(this.options, options)) { - var activeRules = this.createActiveRules(options); - var rulesMap = formatting.RulesMap.create(activeRules); - this.activeRules = activeRules; - this.rulesMap = rulesMap; this.options = ts.clone(options); } }; - RulesProvider.prototype.createActiveRules = function (options) { - var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterConstructor) { - rules.push(this.globalRules.SpaceAfterConstructor); - } - else { - rules.push(this.globalRules.NoSpaceAfterConstructor); - } - if (options.insertSpaceAfterCommaDelimiter) { - rules.push(this.globalRules.SpaceAfterComma); - } - else { - rules.push(this.globalRules.NoSpaceAfterComma); - } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { - rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); - } - else { - rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); - } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { - rules.push(this.globalRules.SpaceAfterKeywordInControl); - } - else { - rules.push(this.globalRules.NoSpaceAfterKeywordInControl); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { - rules.push(this.globalRules.SpaceAfterOpenParen); - rules.push(this.globalRules.SpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenParen); - rules.push(this.globalRules.NoSpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { - rules.push(this.globalRules.SpaceAfterOpenBracket); - rules.push(this.globalRules.SpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBracket); - rules.push(this.globalRules.NoSpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { - rules.push(this.globalRules.SpaceAfterOpenBrace); - rules.push(this.globalRules.SpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBrace); - rules.push(this.globalRules.NoSpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { - rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); - } - else { - rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { - rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); - } - if (options.insertSpaceAfterSemicolonInForStatements) { - rules.push(this.globalRules.SpaceAfterSemicolonInFor); - } - else { - rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); - } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { - rules.push(this.globalRules.SpaceBeforeBinaryOperator); - rules.push(this.globalRules.SpaceAfterBinaryOperator); - } - else { - rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); - rules.push(this.globalRules.NoSpaceAfterBinaryOperator); - } - if (options.insertSpaceBeforeFunctionParenthesis) { - rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl); - } - else { - rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl); - } - if (options.placeOpenBraceOnNewLineForControlBlocks) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); - } - if (options.placeOpenBraceOnNewLineForFunctions) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); - rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); - } - if (options.insertSpaceAfterTypeAssertion) { - rules.push(this.globalRules.SpaceAfterTypeAssertion); - } - else { - rules.push(this.globalRules.NoSpaceAfterTypeAssertion); - } - rules = rules.concat(this.globalRules.LowPriorityCommonRules); - return rules; - }; return RulesProvider; }()); formatting.RulesProvider = RulesProvider; @@ -68067,7 +69041,7 @@ var ts; return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end), options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { - var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRangeHasError; var previousRange; var previousParent; @@ -68150,7 +69124,7 @@ var ts; } case 149: case 146: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -68923,9 +69897,7 @@ var ts; if (node.kind === 20) { return -1; } - if (node.parent && (node.parent.kind === 181 || - node.parent.kind === 182) && - node.parent.expression !== node) { + if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { @@ -69421,7 +70393,7 @@ var ts; }()); textChanges.ChangeTracker = ChangeTracker; function getNonformattedText(node, sourceFile, newLine) { - var options = { newLine: newLine, target: sourceFile.languageVersion }; + var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); printer.writeNode(3, node, sourceFile, writer); @@ -69450,27 +70422,8 @@ var ts; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } - var nullTransformationContext = { - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: function () { return undefined; }, - getCompilerOptions: ts.notImplemented, - getEmitHost: ts.notImplemented, - getEmitResolver: ts.notImplemented, - hoistFunctionDeclaration: ts.noop, - hoistVariableDeclaration: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop - }; function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); var newNode = ts.nodeIsSynthesized(visited) ? visited : (Proxy.prototype = visited, new Proxy()); @@ -69513,6 +70466,16 @@ var ts; setEnd(nodes, _this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; } Writer.prototype.setLastNonTriviaPosition = function (s, force) { if (force || !isTrivia(s)) { @@ -69579,14 +70542,14 @@ var ts; var codefix; (function (codefix) { var codeFixes = []; - function registerCodeFix(action) { - ts.forEach(action.errorCodes, function (error) { + function registerCodeFix(codeFix) { + ts.forEach(codeFix.errorCodes, function (error) { var fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } codefix.registerCodeFix = registerCodeFix; @@ -69609,6 +70572,48 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + var refactors = ts.createMap(); + function registerRefactor(refactor) { + refactors.set(refactor.name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + var results; + var refactorList = []; + refactors.forEach(function (refactor) { + refactorList.push(refactor); + }); + for (var _i = 0, refactorList_1 = refactorList; _i < refactorList_1.length; _i++) { + var refactor_2 = refactorList_1[_i]; + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor_2.isApplicable(context)) { + (results || (results = [])).push({ name: refactor_2.name, description: refactor_2.description }); + } + } + return results; + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getRefactorCodeActions(context, refactorName) { + var result; + var refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + var codeActions = refactor.getCodeActions(context); + if (codeActions) { + ts.addRange((result || (result = [])), codeActions); + } + return result; + } + refactor_1.getRefactorCodeActions = getRefactorCodeActions; + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -69672,7 +70677,8 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { @@ -69750,7 +70756,7 @@ var ts; if (!isStatic) { var stringTypeNode = ts.createKeywordTypeNode(136); var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); - var indexSignature = ts.createIndexSignatureDeclaration(undefined, undefined, [indexingParameter], typeNode); + var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); indexSignatureChangeTracker.insertNodeAfter(sourceFile, openBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ @@ -69764,6 +70770,56 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + function getActionsForCorrectSpelling(context) { + var sourceFile = context.sourceFile; + var node = ts.getTokenAtPosition(sourceFile, context.span.start); + var checker = context.program.getTypeChecker(); + var suggestion; + if (node.kind === 71 && ts.isPropertyAccessExpression(node.parent)) { + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else { + var meaning = ts.getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4) { + flags |= 1920; + } + if (meaning & 2) { + flags |= 793064; + } + if (meaning & 1) { + flags |= 107455; + } + return flags; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -69952,120 +71008,125 @@ var ts; } switch (token.kind) { case 71: - switch (token.parent.kind) { - case 226: - switch (token.parent.parent.parent.kind) { - case 214: - var forStatement = token.parent.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(token.parent); - } - case 216: - var forOfStatement = token.parent.parent.parent; - if (forOfStatement.initializer.kind === 227) { - var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); - } - break; - case 215: - return undefined; - case 260: - var catchClause = token.parent.parent; - var parameter = catchClause.variableDeclaration.getChildren()[0]; - return deleteNode(parameter); - default: - var variableStatement = token.parent.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); - } - else { - return deleteNodeInList(token.parent); - } - } - case 145: - var typeParameters = token.parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); - if (!previousToken || previousToken.kind !== 27) { - return deleteRange(typeParameters); - } - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); - if (!nextToken || nextToken.kind !== 29) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); - } - else { - return deleteNodeInList(token.parent); - } - case 146: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } - case 237: - var importEquals = ts.getAncestor(token, 237); - return deleteNode(importEquals); - case 242: - var namedImports = token.parent.parent; - if (namedImports.elements.length === 1) { - var importSpec = ts.getAncestor(token, 238); - return deleteNode(importSpec); - } - else { - return deleteNodeInList(token.parent); - } - case 239: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238); - return deleteNode(importDecl); - } - else { - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26) { - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); - } - else { - return deleteNode(importClause.name); - } - } - case 240: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { - var importDecl = ts.getAncestor(namespaceImport, 238); - return deleteNode(importDecl); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); - if (previousToken && previousToken.kind === 26) { - var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); - } - return deleteRange(namespaceImport); - } - } - break; + return deleteIdentifier(); case 149: case 240: return deleteNode(token.parent); + default: + return deleteDefault(); } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + function deleteIdentifier() { + switch (token.parent.kind) { + case 226: + return deleteVariableDeclaration(token.parent); + case 145: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); + if (!previousToken || previousToken.kind !== 27) { + return deleteRange(typeParameters); + } + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); + if (!nextToken || nextToken.kind !== 29) { + return deleteRange(typeParameters); + } + return deleteNodeRange(previousToken, nextToken); + } + else { + return deleteNodeInList(token.parent); + } + case 146: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return deleteNode(token.parent); + } + else { + return deleteNodeInList(token.parent); + } + case 237: + var importEquals = ts.getAncestor(token, 237); + return deleteNode(importEquals); + case 242: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + var importSpec = ts.getAncestor(token, 238); + return deleteNode(importSpec); + } + else { + return deleteNodeInList(token.parent); + } + case 239: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = ts.getAncestor(importClause, 238); + return deleteNode(importDecl); + } + else { + var start_4 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 26) { + return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); + } + else { + return deleteNode(importClause.name); + } + } + case 240: + var namespaceImport = token.parent; + if (namespaceImport.name === token && !namespaceImport.parent.name) { + var importDecl = ts.getAncestor(namespaceImport, 238); + return deleteNode(importDecl); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); + if (previousToken && previousToken.kind === 26) { + var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); + return deleteRange({ pos: startPosition, end: namespaceImport.end }); + } + return deleteRange(namespaceImport); + } + default: + return deleteDefault(); + } } - else { - return undefined; + function deleteVariableDeclaration(varDecl) { + switch (varDecl.parent.parent.kind) { + case 214: + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return deleteNode(forInitializer); + } + else { + return deleteNodeInList(varDecl); + } + case 216: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 227); + var forOfInitializer = forOfStatement.initializer; + return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + case 215: + return undefined; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return deleteNode(variableStatement); + } + else { + return deleteNodeInList(varDecl); + } + } } function deleteNode(n) { return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); @@ -70096,6 +71157,15 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ], + getCodeActions: getImportCodeActions + }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; @@ -70178,342 +71248,335 @@ var ts; }; return ImportCodeActionMap; }()); - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); - return getCodeActionForImport(symbol, false, true); + function getImportCodeActions(context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + var cachedImportDeclarations = []; + var lastImportDeclaration; + var currentTokenMeaning = ts.getMeaningFromLocation(token); + if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); + return getCodeActionForImport(symbol, false, true); + } + var candidateModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + candidateModules.push(otherSourceFile.symbol); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); + } + for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { + var moduleSymbol = candidateModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); } } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (cached) { + return cached; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 238) { + return node; } - } - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); - } - } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + if (node.kind === 237) { + return node; } + node = node.parent; } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238) { - return node; + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + if (declaration.kind === 238) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 240) { + namespaceImportDeclaration = declaration; } - if (node.kind === 237) { - return node; + else { + namedImportDeclaration = declaration; } - node = node.parent; + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - return undefined; } - } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); } - return ts.getSymbolId(symbol); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; - } - function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - return getCodeActionsForExistingImport(existingDeclarations); + if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); } else { - return [getCodeActionForNewImport()]; + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; - if (declaration.kind === 238) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240) { - namespaceImportDeclaration = declaration; - } - else { - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248) { + return declaration.moduleReference.expression.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var importList = importClause.namedBindings; + var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); + if (!importList || importList.elements.length === 0) { + var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); + return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 238) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); } else { - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + namespacePrefix = declaration.name.getText(); } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248) { - return declaration.moduleReference.expression.getText(); + namespacePrefix = ts.stripQuotes(namespacePrefix); + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!lastImportDeclaration) { + for (var i = sourceFile.statements.length - 1; i >= 0; i--) { + var statement = sourceFile.statements[i]; + if (statement.kind === 237 || statement.kind === 238) { + lastImportDeclaration = statement; + break; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); - } - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 || statement.kind === 238) { - lastImportDeclaration = statement; - break; - } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var changeTracker = createChangeTracker(); + var importClause = isDefault + ? ts.createImportClause(ts.createIdentifier(name), undefined) + : isNamespaceImport + ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) + : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); + var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + if (!lastImportDeclaration) { + changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); + } + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.fileName; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 265) { + return moduleSymbol.name; } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), undefined) - : isNamespaceImport - ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); - var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265) { - return moduleSymbol.name; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { return undefined; } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); + if (!relativeName) { + return undefined; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - return undefined; - } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { - return undefined; - } - var relativeFileName; - if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { - relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); - } - else { - relativeFileName = getRelativePath(moduleFileName, sourceDirectory); - } - relativeFileName = ts.removeFileExtension(relativeFileName); - if (ts.endsWith(relativeFileName, "/index")) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } - else { - try { - var moduleDirectory = ts.getDirectoryPath(moduleFileName); - var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); - if (packageJsonContent) { - var mainFile = packageJsonContent.main || packageJsonContent.typings; - if (mainFile) { - var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; + } } - catch (e) { } } - return relativeFileName; } + return relativeName; } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); } } return undefined; } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6); + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } } - return fileName; } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; - } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; } } - } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); - } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = getRelativePathIfInDirectory(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } } } - }); + function createChangeTracker() { + return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + } + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; @@ -70628,7 +71691,7 @@ var ts; return undefined; } var declaration = declarations[0]; - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -70677,7 +71740,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -70718,7 +71781,7 @@ var ts; return createStubbedMethod(modifiers, name, optional, undefined, parameters, undefined); } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethodDeclaration(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); + return ts.createMethod(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } codefix.createStubbedMethod = createStubbedMethod; function createStubbedMethodBody() { @@ -70736,8 +71799,173 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor) { + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions: getCodeActions, + isApplicable: isApplicable + }; + refactor.registerRefactor(convertFunctionToES6Class); + function isApplicable(context) { + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + return symbol && symbol.flags & 16 && symbol.members && symbol.members.size > 0; + } + function getCodeActions(context) { + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 | 3))) { + return []; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 228: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 226: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return []; + } + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { + var deleteCallback = deletes_1[_i]; + deleteCallback(); + } + return [{ + description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); + } + else { + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); + } + } + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(115)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + if (!(symbol.flags & 4)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 186: + var functionExpression = assignmentBinaryExpression.right; + return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); + case 187: + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + if (arrowFunctionBody.kind === 207) { + bodyBlock = arrowFunctionBody; + } + else { + var expression = arrowFunctionBody; + bodyBlock = ts.createBlock([ts.createReturn(expression)]); + } + return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); + default: + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + return ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 186) { + return undefined; + } + if (node.name.kind !== 71) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body)); + } + return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); + } + return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + } + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.servicesVersion = "0.5"; + var ruleProvider; function createNode(kind, pos, end, parent) { var node = kind >= 143 ? new NodeObject(kind, pos, end) : kind === 71 ? new IdentifierObject(71, pos, end) : @@ -71116,13 +72344,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_7 !== undefined) { - return result_7; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_8 = getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (declaration.name.kind === 144) { - var expr = declaration.name.expression; + if (name.kind === 144) { + var expr = name.expression; if (expr.kind === 179) { return expr.name.text; } @@ -71465,7 +72694,7 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - var ruleProvider; + ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -71489,9 +72718,6 @@ var ts; return sourceFile; } function getRuleProvider(options) { - if (!ruleProvider) { - ruleProvider = new ts.formatting.RulesProvider(); - } ruleProvider.ensureUpToDate(options); return ruleProvider; } @@ -71718,7 +72944,7 @@ var ts; } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); @@ -71732,7 +72958,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); @@ -71765,11 +72991,11 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); @@ -72017,8 +73243,7 @@ var ts; ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); var preamble = matchArray[1]; var matchPosition = matchArray.index + preamble.length; - var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!ts.isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInComment(sourceFile, matchPosition)) { continue; } var descriptor = undefined; @@ -72066,11 +73291,35 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file, positionOrRange, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken: cancellationToken + }; + } + function getApplicableRefactors(fileName, positionOrRange) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getApplicableRefactors: getApplicableRefactors, + getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -72184,20 +73433,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = ts.getTextOfPropertyName(node.name); if (name && contextualType) { - var result_8 = []; + var result_9 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_8.push(symbol); + result_9.push(symbol); } }); - return result_8; + return result_9; } if (symbol) { - result_8.push(symbol); - return result_8; + result_9.push(symbol); + return result_9; } } return undefined; @@ -72734,6 +73983,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations @@ -74423,7 +75675,7 @@ var ts; var oldProgram = this.program; this.program = this.languageService.getProgram(); var hasChanges = false; - if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { + if (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2))) { hasChanges = true; if (oldProgram) { for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { @@ -74680,6 +75932,11 @@ var ts; return; } var searchPaths = [ts.combinePaths(host.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"); + searchPaths.unshift(local); + } if (options.plugins) { for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { var pluginConfigEntry = _a[_i]; @@ -75064,6 +76321,7 @@ var ts; this.eventHandler = opts.eventHandler; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; + this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.directoryWatchers = new DirectoryWatchers(this); @@ -76263,6 +77521,9 @@ var ts; CommandNames.GetCodeFixes = "getCodeFixes"; CommandNames.GetCodeFixesFull = "getCodeFixes-full"; CommandNames.GetSupportedCodeFixes = "getSupportedCodeFixes"; + CommandNames.GetApplicableRefactors = "getApplicableRefactors"; + CommandNames.GetRefactorCodeActions = "getRefactorCodeActions"; + CommandNames.GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); function formatMessage(msg, logger, byteLength, newLine) { var verboseLogging = logger.hasLevel(server.LogLevel.verbose); @@ -76596,6 +77857,15 @@ var ts; _a[CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); }, + _a[CommandNames.GetApplicableRefactors] = function (request) { + return _this.requiredResponse(_this.getApplicableRefactors(request.arguments)); + }, + _a[CommandNames.GetRefactorCodeActions] = function (request) { + return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, true)); + }, + _a[CommandNames.GetRefactorCodeActionsFull] = function (request) { + return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, false)); + }, _a)); this.host = opts.host; this.cancellationToken = opts.cancellationToken; @@ -76626,7 +77896,8 @@ var ts; throttleWaitMilliseconds: throttleWaitMilliseconds, eventHandler: this.eventHandler, globalPlugins: opts.globalPlugins, - pluginProbeLocations: opts.pluginProbeLocations + pluginProbeLocations: opts.pluginProbeLocations, + allowLocalPluginLoads: opts.allowLocalPluginLoads }; this.projectService = new server.ProjectService(settings); this.gcTimer = new server.GcTimer(this.host, 7000, this.logger); @@ -77562,6 +78833,47 @@ var ts; Session.prototype.getSupportedCodeFixes = function () { return ts.getSupportedCodeFixes(); }; + Session.prototype.isLocation = function (locationOrSpan) { + return locationOrSpan.line !== undefined; + }; + Session.prototype.extractPositionAndRange = function (args, scriptInfo) { + var position = undefined; + var textRange; + if (this.isLocation(args)) { + position = getPosition(args); + } + else { + var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition; + textRange = { pos: startPosition, end: endPosition }; + } + return { position: position, textRange: textRange }; + function getPosition(loc) { + return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); + } + }; + Session.prototype.getApplicableRefactors = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; + return project.getLanguageService().getApplicableRefactors(file, position || textRange); + }; + Session.prototype.getRefactorCodeActions = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; + var result = project.getLanguageService().getRefactorCodeActions(file, this.projectService.getFormatCodeOptions(), position || textRange, args.refactorName); + if (simplifiedResult) { + return { + actions: result.map(function (action) { return _this.mapCodeAction(action, scriptInfo); }) + }; + } + else { + return { + actions: result + }; + } + }; Session.prototype.getCodeFixes = function (args, simplifiedResult) { var _this = this; if (args.errorCodes.length === 0) { @@ -77569,8 +78881,7 @@ var ts; } var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var startPosition = getStartPosition(); - var endPosition = getEndPosition(); + var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; var formatOptions = this.projectService.getFormatCodeOptions(file); var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, formatOptions); if (!codeActions) { @@ -77582,12 +78893,24 @@ var ts; else { return codeActions; } - function getStartPosition() { - return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + }; + Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { + var startPosition = undefined, endPosition = undefined; + if (args.startPosition !== undefined) { + startPosition = args.startPosition; } - function getEndPosition() { - return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + else { + startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + args.startPosition = startPosition; } + if (args.endPosition !== undefined) { + endPosition = args.endPosition; + } + else { + endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + args.endPosition = endPosition; + } + return { startPosition: startPosition, endPosition: endPosition }; }; Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { var _this = this; @@ -78878,7 +80201,8 @@ var ts; logger: logger, canUseEvents: canUseEvents, globalPlugins: options.globalPlugins, - pluginProbeLocations: options.pluginProbeLocations + pluginProbeLocations: options.pluginProbeLocations, + allowLocalPluginLoads: options.allowLocalPluginLoads }) || this; if (telemetryEnabled && typingsInstaller) { typingsInstaller.setTelemetrySender(_this); @@ -79121,12 +80445,11 @@ var ts; sys.gc = function () { return global.gc(); }; } sys.require = function (initialDir, moduleName) { - var result = ts.nodeModuleNameResolverWorker(moduleName, initialDir + "/program.ts", { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, sys, undefined, true); try { - return { module: require(result.resolvedModule.resolvedFileName), error: undefined }; + return { module: require(ts.resolveJavaScriptModule(moduleName, initialDir, sys)), error: undefined }; } - catch (e) { - return { module: undefined, error: e }; + catch (error) { + return { module: undefined, error: error }; } }; var cancellationToken; @@ -79152,6 +80475,7 @@ var ts; var typingSafeListLocation = server.findArgument("--typingSafeListLocation"); var globalPlugins = (server.findArgument("--globalPlugins") || "").split(","); var pluginProbeLocations = (server.findArgument("--pluginProbeLocations") || "").split(","); + var allowLocalPluginLoads = server.hasArgument("--allowLocalPluginLoads"); var useSingleInferredProject = server.hasArgument("--useSingleInferredProject"); var disableAutomaticTypingAcquisition = server.hasArgument("--disableAutomaticTypingAcquisition"); var telemetryEnabled = server.hasArgument(server.Arguments.EnableTelemetry); @@ -79167,7 +80491,8 @@ var ts; telemetryEnabled: telemetryEnabled, logger: logger, globalPlugins: globalPlugins, - pluginProbeLocations: pluginProbeLocations + pluginProbeLocations: pluginProbeLocations, + allowLocalPluginLoads: allowLocalPluginLoads }; var ioSession = new IOSession(options); process.on("uncaughtException", function (err) { @@ -79177,3 +80502,5 @@ var ts; ioSession.listen(); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); + +//# sourceMappingURL=tsserver.js.map diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 189883c63e6..643a9e80d06 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -352,9 +352,10 @@ declare namespace ts { SyntaxList = 294, NotEmittedStatement = 295, PartiallyEmittedExpression = 296, - MergeDeclarationMarker = 297, - EndOfDeclarationMarker = 298, - Count = 299, + CommaListExpression = 297, + MergeDeclarationMarker = 298, + EndOfDeclarationMarker = 299, + Count = 300, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -482,9 +483,11 @@ declare namespace ts { type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { name?: DeclarationName; } - interface DeclarationStatement extends Declaration, Statement { + interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { @@ -495,7 +498,7 @@ declare namespace ts { kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } - interface TypeParameterDeclaration extends Declaration { + interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -503,7 +506,7 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends Declaration { + interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -516,7 +519,7 @@ declare namespace ts { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; - interface VariableDeclaration extends Declaration { + interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; @@ -528,7 +531,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends Declaration { + interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -537,7 +540,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface BindingElement extends Declaration { + interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; @@ -559,7 +562,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface ObjectLiteralElement extends Declaration { + interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -581,7 +584,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends Declaration { + interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -589,7 +592,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface PropertyLikeDeclaration extends Declaration { + interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } interface ObjectBindingPattern extends Node { @@ -926,7 +929,7 @@ declare namespace ts { } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - interface PropertyAccessExpression extends MemberExpression, Declaration { + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -991,7 +994,7 @@ declare namespace ts { } interface MetaProperty extends PrimaryExpression { kind: SyntaxKind.MetaProperty; - keywordToken: SyntaxKind; + keywordToken: SyntaxKind.NewKeyword; name: Identifier; } interface JsxElement extends PrimaryExpression { @@ -1051,6 +1054,10 @@ declare namespace ts { interface NotEmittedStatement extends Statement { kind: SyntaxKind.NotEmittedStatement; } + interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; + elements: NodeArray; + } interface EmptyStatement extends Statement { kind: SyntaxKind.EmptyStatement; } @@ -1172,7 +1179,7 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - interface ClassLikeDeclaration extends Declaration { + interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1185,11 +1192,11 @@ declare namespace ts { interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { kind: SyntaxKind.ClassExpression; } - interface ClassElement extends Declaration { + interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - interface TypeElement extends Declaration { + interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1213,7 +1220,7 @@ declare namespace ts { typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends Declaration { + interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; @@ -1266,13 +1273,13 @@ declare namespace ts { moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; - interface ImportClause extends Declaration { + interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } - interface NamespaceImport extends Declaration { + interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1298,13 +1305,13 @@ declare namespace ts { elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; - interface ImportSpecifier extends Declaration { + interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; name: Identifier; } - interface ExportSpecifier extends Declaration { + interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; @@ -1435,7 +1442,7 @@ declare namespace ts { kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } - interface JSDocTypedefTag extends JSDocTag, Declaration { + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -1626,11 +1633,11 @@ declare namespace ts { signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration; indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; + getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; - getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; @@ -1640,37 +1647,47 @@ declare namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + getContextualType(node: Expression): Type | undefined; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type; + getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; + getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; + getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; } enum NodeBuilderFlags { None = 0, - allowThisInObjectLiteral = 1, - allowQualifedNameInPlaceOfIdentifier = 2, - allowTypeParameterInQualifiedName = 4, - allowAnonymousIdentifier = 8, - allowEmptyUnionOrIntersection = 16, - allowEmptyTuple = 32, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + AllowThisInObjectLiteral = 1024, + AllowQualifedNameInPlaceOfIdentifier = 2048, + AllowAnonymousIdentifier = 8192, + AllowEmptyUnionOrIntersection = 16384, + AllowEmptyTuple = 32768, + IgnoreErrors = 60416, + InObjectTypeLiteral = 1048576, + InTypeAlias = 8388608, } interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1831,18 +1848,18 @@ declare namespace ts { Index = 262144, IndexedAccess = 524288, NonPrimitive = 16777216, - Literal = 480, + Literal = 224, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, StringLike = 262178, - NumberLike = 340, + NumberLike = 84, BooleanLike = 136, EnumLike = 272, UnionOrIntersection = 196608, StructuredType = 229376, StructuredOrTypeVariable = 1032192, TypeVariable = 540672, - Narrowable = 17810431, + Narrowable = 17810175, NotUnionOrUnit = 16810497, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; @@ -1854,15 +1871,17 @@ declare namespace ts { aliasTypeArguments?: Type[]; } interface LiteralType extends Type { - text: string; + value: string | number; freshType?: LiteralType; regularType?: LiteralType; } - interface EnumType extends Type { - memberTypes: EnumLiteralType[]; + interface StringLiteralType extends LiteralType { + value: string; } - interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; + interface NumberLiteralType extends LiteralType { + value: number; + } + interface EnumType extends Type { } const enum ObjectFlags { Class = 1, @@ -1896,7 +1915,7 @@ declare namespace ts { } interface TypeReference extends ObjectType { target: GenericType; - typeArguments: Type[]; + typeArguments?: Type[]; } interface GenericType extends InterfaceType, TypeReference { } @@ -1932,7 +1951,7 @@ declare namespace ts { } interface Signature { declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; + typeParameters?: TypeParameter[]; parameters: Symbol[]; } const enum IndexKind { @@ -1961,9 +1980,9 @@ declare namespace ts { next?: DiagnosticMessageChain; } interface Diagnostic { - file: SourceFile; - start: number; - length: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; messageText: string | DiagnosticMessageChain; category: DiagnosticCategory; code: number; @@ -2204,6 +2223,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, + NoAsciiEscaping = 16777216, } interface EmitHelper { readonly name: string; @@ -2362,13 +2382,13 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; - function getShebang(text: string): string; + function getShebang(text: string): string | undefined; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; @@ -2384,7 +2404,7 @@ declare namespace ts { error?: Diagnostic; }; function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine; - function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -2395,9 +2415,6 @@ declare namespace ts { }; } declare namespace ts { - interface Push { - push(value: T): void; - } function moduleHasNonRelativeName(moduleName: string): boolean; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; @@ -2466,6 +2483,7 @@ declare namespace ts { function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; + function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; function createLoopVariable(): Identifier; function createUniqueName(text: string): Identifier; @@ -2480,58 +2498,19 @@ declare namespace ts { function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; - function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): SignatureDeclaration; - function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; - function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; - function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; - function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; - function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; - function createThisTypeNode(): ThisTypeNode; - function createLiteralTypeNode(literal: Expression): LiteralTypeNode; - function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; - function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; - function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; - function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; - function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; - function createTypeQueryNode(exprName: EntityName): TypeQueryNode; - function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; - function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; - function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray): UnionOrIntersectionTypeNode; - function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; - function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; - function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; - function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; - function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; - function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; - function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; - function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; - function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; function createDecorator(expression: Expression): Decorator; function updateDecorator(node: Decorator, expression: Expression): Decorator; + function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; - function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function createConstructor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; @@ -2539,6 +2518,45 @@ declare namespace ts { function updateGetAccessor(node: GetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; function createSetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; function updateSetAccessor(node: SetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; + function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; + function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; + function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; + function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; + function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; + function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; + function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; + function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; + function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; + function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; + function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; + function createTypeQueryNode(exprName: EntityName): TypeQueryNode; + function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; + function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; + function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; + function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; + function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; + function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; + function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; + function createUnionTypeNode(types: TypeNode[]): UnionTypeNode; + function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; + function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode; + function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionTypeNode | IntersectionTypeNode; + function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; + function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; + function createThisTypeNode(): ThisTypeNode; + function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; + function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function createLiteralTypeNode(literal: Expression): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; function createObjectBindingPattern(elements: BindingElement[]): ObjectBindingPattern; function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern; function createArrayBindingPattern(elements: ArrayBindingElement[]): ArrayBindingPattern; @@ -2580,7 +2598,7 @@ declare namespace ts { function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; - function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression; + function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; @@ -2600,16 +2618,15 @@ declare namespace ts { function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; function createNonNullExpression(expression: Expression): NonNullExpression; function updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression; + function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function createSemicolonClassElement(): SemicolonClassElement; function createBlock(statements: Statement[], multiLine?: boolean): Block; function updateBlock(node: Block, statements: Statement[]): Block; function createVariableStatement(modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList | VariableDeclaration[]): VariableStatement; function updateVariableStatement(node: VariableStatement, modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList): VariableStatement; - function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; - function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; - function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; - function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; function createEmptyStatement(): EmptyStatement; function createStatement(expression: Expression): ExpressionStatement; function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; @@ -2641,10 +2658,19 @@ declare namespace ts { function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement; function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function createDebuggerStatement(): DebuggerStatement; + function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; + function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; + function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function createClassDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; + function createInterfaceDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; function createEnumDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, members: EnumMember[]): EnumDeclaration; function updateEnumDeclaration(node: EnumDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, members: EnumMember[]): EnumDeclaration; function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; @@ -2653,6 +2679,8 @@ declare namespace ts { function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock; function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock; function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; + function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function createImportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; @@ -2683,20 +2711,20 @@ declare namespace ts { function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; - function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; - function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; - function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; - function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCaseClause(expression: Expression, statements: Statement[]): CaseClause; function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]): CaseClause; function createDefaultClause(statements: Statement[]): DefaultClause; function updateDefaultClause(node: DefaultClause, statements: Statement[]): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause; function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause; function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; @@ -2712,6 +2740,8 @@ declare namespace ts { function createNotEmittedStatement(original: Node): NotEmittedStatement; function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createCommaList(elements: Expression[]): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: Expression[]): CommaListExpression; function createBundle(sourceFiles: SourceFile[]): Bundle; function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; function createComma(left: Expression, right: Expression): Expression; @@ -2745,8 +2775,8 @@ declare namespace ts { function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T; function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; - function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; - function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression; function addEmitHelper(node: T, helper: EmitHelper): T; function addEmitHelpers(node: T, helpers: EmitHelper[] | undefined): T; function removeEmitHelper(node: Node, helper: EmitHelper): boolean; @@ -2756,7 +2786,7 @@ declare namespace ts { } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; - function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; function isExternalModule(file: SourceFile): boolean; @@ -2789,6 +2819,7 @@ declare namespace ts { getNewLine(): string; } function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } @@ -2931,6 +2962,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; + getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -2981,6 +3014,10 @@ declare namespace ts { description: string; changes: FileTextChanges[]; } + interface ApplicableRefactorInfo { + name: string; + description: string; + } interface TextInsertion { newText: string; caretOffset: number; @@ -3367,6 +3404,7 @@ declare namespace ts { reportDiagnostics?: boolean; moduleName?: string; renamedDependencies?: MapLike; + transformers?: CustomTransformers; } interface TranspileOutput { outputText: string; @@ -3610,6 +3648,9 @@ declare namespace ts.server.protocol { type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; type GetCodeFixes = "getCodeFixes"; type GetSupportedCodeFixes = "getSupportedCodeFixes"; + type GetApplicableRefactors = "getApplicableRefactors"; + type GetRefactorCodeActions = "getRefactorCodeActions"; + type GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; } interface Message { seq: number; @@ -3704,15 +3745,44 @@ declare namespace ts.server.protocol { line: number; offset: number; } + type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + interface GetApplicableRefactorsRequest extends Request { + command: CommandTypes.GetApplicableRefactors; + arguments: GetApplicableRefactorsRequestArgs; + } + type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs; + interface ApplicableRefactorInfo { + name: string; + description: string; + } + interface GetApplicableRefactorsResponse extends Response { + body?: ApplicableRefactorInfo[]; + } + interface GetRefactorCodeActionsRequest extends Request { + command: CommandTypes.GetRefactorCodeActions; + arguments: GetRefactorCodeActionsRequestArgs; + } + type GetRefactorCodeActionsRequestArgs = FileLocationOrRangeRequestArgs & { + refactorName: string; + }; + type RefactorCodeActions = { + actions: protocol.CodeAction[]; + renameLocation?: number; + }; + interface GetRefactorCodeActionsResponse extends Response { + body: RefactorCodeActions; + } interface CodeFixRequest extends Request { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; } - interface CodeFixRequestArgs extends FileRequestArgs { + interface FileRangeRequestArgs extends FileRequestArgs { startLine: number; startOffset: number; endLine: number; endOffset: number; + } + interface CodeFixRequestArgs extends FileRangeRequestArgs { errorCodes?: number[]; } interface GetCodeFixesResponse extends Response { @@ -4291,6 +4361,7 @@ declare namespace ts.server.protocol { insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; @@ -4408,7 +4479,7 @@ declare namespace ts.server { project: Project; } interface EventSender { - event(payload: any, eventName: string): void; + event(payload: T, eventName: string): void; } namespace CommandNames { const Brace: protocol.CommandTypes.Brace; @@ -4455,6 +4526,9 @@ declare namespace ts.server { const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects; const GetCodeFixes: protocol.CommandTypes.GetCodeFixes; const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes; + const GetApplicableRefactors: protocol.CommandTypes.GetApplicableRefactors; + const GetRefactorCodeActions: protocol.CommandTypes.GetRefactorCodeActions; + const GetRefactorCodeActionsFull: protocol.CommandTypes.GetRefactorCodeActionsFull; } function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; interface SessionOptions { @@ -4470,6 +4544,7 @@ declare namespace ts.server { throttleWaitMilliseconds?: number; globalPlugins?: string[]; pluginProbeLocations?: string[]; + allowLocalPluginLoads?: boolean; } class Session implements EventSender { private readonly gcTimer; @@ -4491,7 +4566,7 @@ declare namespace ts.server { logError(err: Error, cmd: string): void; send(msg: protocol.Message): void; configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ts.Diagnostic[]): void; - event(info: any, eventName: string): void; + event(info: T, eventName: string): void; output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void; private semanticCheck(file, project); private syntacticCheck(file, project); @@ -4554,7 +4629,12 @@ declare namespace ts.server { private getNavigationTree(args, simplifiedResult); private getNavigateToItems(args, simplifiedResult); private getSupportedCodeFixes(); + private isLocation(locationOrSpan); + private extractPositionAndRange(args, scriptInfo); + private getApplicableRefactors(args); + private getRefactorCodeActions(args, simplifiedResult); private getCodeFixes(args, simplifiedResult); + private getStartAndEndPosition(args, scriptInfo); private mapCodeAction(codeAction, scriptInfo); private convertTextChangeToCodeEdit(change, scriptInfo); private getBraceMatching(args, simplifiedResult); @@ -5047,6 +5127,7 @@ declare namespace ts.server { throttleWaitMilliseconds?: number; globalPlugins?: string[]; pluginProbeLocations?: string[]; + allowLocalPluginLoads?: boolean; } class ProjectService { readonly typingsCache: TypingsCache; @@ -5076,6 +5157,7 @@ declare namespace ts.server { private readonly eventHandler?; readonly globalPlugins: ReadonlyArray; readonly pluginProbeLocations: ReadonlyArray; + readonly allowLocalPluginLoads: boolean; constructor(opts: ProjectServiceOptions); ensureInferredProjectsUpToDate_TestOnly(): void; getCompilerOptionsForInferredProjects(): CompilerOptions; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 52c8a2207c4..128438ce66a 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -332,9 +332,10 @@ var ts; SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; @@ -469,6 +470,12 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -478,12 +485,20 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { @@ -604,6 +619,11 @@ var ts; SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); var CheckFlags; (function (CheckFlags) { CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; @@ -671,21 +691,21 @@ var ts; TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; - TypeFlags[TypeFlags["Narrowable"] = 17810431] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; @@ -1011,6 +1031,7 @@ var ts; EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1025,14 +1046,17 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1288,6 +1312,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; function every(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1492,6 +1525,28 @@ var ts; return result; } ts.flatMap = flatMap; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -2516,6 +2571,10 @@ var ts; return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -3571,6 +3630,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -3678,7 +3738,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -3873,6 +3933,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4168,6 +4236,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -4213,6 +4282,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4294,6 +4365,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -4842,9 +4916,10 @@ var ts; } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -6004,6 +6079,7 @@ var ts; "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -6855,49 +6931,28 @@ var ts; if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + if (exclude) { + json.exclude = exclude; } - if (include && !json["include"]) { - json["include"] = include; + if (files) { + json.files = files; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } + return options; + })(); options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -6907,37 +6962,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -6968,9 +6993,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; @@ -6987,9 +7009,66 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -7245,12 +7324,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -7534,6 +7612,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -7667,12 +7747,18 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -7702,7 +7788,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -8087,9 +8172,7 @@ var ts; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -8246,26 +8329,28 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; } @@ -8472,10 +8557,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 && isConst(node); } @@ -8727,6 +8808,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160: + case 161: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151: @@ -8951,6 +9041,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 || node.kind === 182; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183) { return node.tag; @@ -9504,21 +9598,46 @@ var ts; } ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { - if (name.kind !== 71 && name.kind !== 9 && name.kind !== 8) { - return false; + switch (name.kind) { + case 71: + case 9: + case 8: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 || parent.kind === 246) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0: + case 2: + return undefined; + case 1: + if (lhs.kind === 71) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4: + case 5: + return lhs.name; + case 3: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 144 && @@ -9618,21 +9737,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -9660,12 +9777,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4; + } var flags = 0; switch (node.kind) { case 228: @@ -9710,7 +9828,8 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -9985,6 +10104,8 @@ var ts; return 2; case 198: return 1; + case 297: + return 0; default: return -1; } @@ -10088,12 +10209,13 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -10182,7 +10304,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -10234,7 +10356,7 @@ var ts; } ts.getSourceFilesToEmit = getSourceFilesToEmit; function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { @@ -10723,13 +10845,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 1: + return lineFeed; } - else if (options.newLine === 1) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -10977,10 +11099,6 @@ var ts; return node.kind === 71; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { return isIdentifier(node) && node.autoGenerateKind > 0; } @@ -11048,9 +11166,20 @@ var ts; || kind === 153 || kind === 154 || kind === 157 - || kind === 206; + || kind === 206 + || kind === 247; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 + || kind === 155 + || kind === 148 + || kind === 150 + || kind === 157 + || kind === 247; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 @@ -11248,6 +11377,7 @@ var ts; || kind === 198 || kind === 202 || kind === 200 + || kind === 297 || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -11334,6 +11464,10 @@ var ts; return node.kind === 237; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239; } @@ -11356,6 +11490,10 @@ var ts; return node.kind === 246; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 || node.kind === 232; } @@ -11427,8 +11565,8 @@ var ts; || kind === 213 || kind === 220 || kind === 295 - || kind === 298 - || kind === 297; + || kind === 299 + || kind === 298; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -11544,6 +11682,48 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + } + if (getCheckFlags(s) & 6) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 ? 8 : + checkFlags & 64 ? 4 : + 16; + var staticModifier = checkFlags & 512 ? 32 : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216) { + return 4 | 32; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11882,15 +12062,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; node.autoGenerateKind = 0; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; function createTempVariable(recordTempVariable) { var name = createIdentifier(""); @@ -11978,237 +12167,12 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170); - typeOperatorNode.operator = 127; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -12219,42 +12183,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146); node.decorators = asNodeArray(decorators); @@ -12291,6 +12219,26 @@ var ts; : node; } ts.updateDecorator = updateDecorator; + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149); node.decorators = asNodeArray(decorators); @@ -12312,7 +12260,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -12325,7 +12290,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -12335,7 +12300,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -12403,6 +12368,249 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170); + node.operator = 127; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174); node.elements = createNodeArray(elements); @@ -12448,9 +12656,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -12463,9 +12670,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -12513,9 +12719,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -12705,10 +12911,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -12835,6 +13041,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205); node.expression = expression; @@ -12849,6 +13068,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206); + } + ts.createSemicolonClassElement = createSemicolonClassElement; function createBlock(statements, multiLine) { var block = createSynthesizedNode(207); block.statements = createNodeArray(statements); @@ -12858,7 +13081,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -12878,35 +13101,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209); } @@ -13125,6 +13319,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227); + node.flags |= flags & 3; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228); node.decorators = asNodeArray(decorators); @@ -13173,6 +13400,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232); node.decorators = asNodeArray(decorators); @@ -13193,7 +13462,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233); - node.flags |= flags; + node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -13234,6 +13503,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237); node.decorators = asNodeArray(decorators); @@ -13264,7 +13545,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -13450,19 +13732,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253); node.name = name; @@ -13477,6 +13746,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255); node.expression = expression; @@ -13502,20 +13783,6 @@ var ts; : node; } ts.updateJsxExpression = updateJsxExpression; - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257); node.expression = ts.parenthesizeExpressionForList(expression); @@ -13524,10 +13791,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -13537,12 +13804,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -13551,10 +13830,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer) { @@ -13566,10 +13845,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -13580,10 +13859,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -13593,10 +13872,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; function createEnumMember(name, initializer) { @@ -13691,14 +13969,14 @@ var ts; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(299); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(298); node.emitNode = {}; node.original = original; return node; @@ -13719,6 +13997,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266); node.sourceFiles = sourceFiles; @@ -14029,6 +14330,25 @@ var ts; } })(ts || (ts = {})); (function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -14269,7 +14589,9 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -14376,9 +14698,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -14489,16 +14812,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 185) { @@ -14667,6 +14980,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166: + case 167: + case 160: + case 161: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { var clone_1 = ts.getMutableClone(originalOuterExpression); @@ -14819,7 +15160,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -15476,6 +15817,8 @@ var ts; return visitNode(cbNode, node.expression); case 247: return visitNodes(cbNodes, node.decorators); + case 297: + return visitNodes(cbNodes, node.elements); case 249: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -19818,6 +20161,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -20578,7 +20923,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -20606,7 +20951,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { return true; } else { @@ -20639,19 +20984,20 @@ var ts; } } function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144) { - var nameExpression = node.name.expression; + if (name.kind === 144) { + var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152: @@ -20747,9 +21093,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -22399,7 +22745,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { @@ -22414,7 +22760,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -22429,7 +22775,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -22442,7 +22788,7 @@ var ts; return bindAnonymousDeclaration(node, 16, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -23177,6 +23523,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -23321,13 +23668,16 @@ var ts; tryFindAmbientModuleWithoutAugmentations: function (moduleName) { return tryFindAmbientModule(moduleName, false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4, "unknown"); @@ -23400,11 +23750,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32, ""); - var zeroType = getLiteralTypeForText(64, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -23661,16 +24013,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 || source.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -23743,9 +24095,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); } @@ -23753,7 +24102,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -23781,7 +24130,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -23856,7 +24206,11 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; var result; var lastLocation; var propertyWithInvalidInitializer; @@ -23865,7 +24219,7 @@ var ts; var isInExternalModule = false; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { if (meaning & result.flags & 793064 && lastLocation.kind !== 283) { @@ -23912,12 +24266,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931)) { + if (result = lookup(moduleExports, name, meaning & 8914931)) { break loop; } break; case 232: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; @@ -23926,7 +24280,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455)) { + if (lookup(ctor.locals, name, meaning & 107455)) { propertyWithInvalidInitializer = location; } } @@ -23935,7 +24289,7 @@ var ts; case 229: case 199: case 230: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -23957,7 +24311,7 @@ var ts; case 144: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -24004,7 +24358,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -24014,7 +24368,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -24111,6 +24475,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -24142,13 +24510,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -24160,7 +24528,7 @@ var ts; if (node.kind === 237) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -24263,10 +24631,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920, false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); @@ -24282,7 +24650,7 @@ var ts; case 242: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); case 243: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236: @@ -24404,7 +24772,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -24424,6 +24792,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, true); if (ambientModule) { return ambientModule; @@ -24483,7 +24856,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -24624,7 +24996,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } function isReservedMemberName(name) { return name.charCodeAt(0) === 95 && @@ -24894,34 +25266,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3, typeNode, sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -24931,12 +25328,12 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; return undefined; @@ -24953,23 +25350,25 @@ var ts; if (type.flags & 8) { return ts.createKeywordTypeNode(122); } - if (type.flags & 16) { - var name = symbolToName(type.symbol, false); + if (type.flags & 256 && !(type.flags & 65536)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064, false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, undefined); + } + if (type.flags & 272) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } if (type.flags & (32)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); } if (type.flags & (64)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } if (type.flags & 1024) { return ts.createKeywordTypeNode(105); } @@ -24989,8 +25388,8 @@ var ts; return ts.createKeywordTypeNode(134); } if (type.flags & 16384 && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -25001,72 +25400,53 @@ var ts; ts.Debug.assert(!!(type.flags & 32768)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3) { - ts.Debug.assert(!!(type.flags & 32768)); - var name = symbolToName(type.symbol, false); + if (type.flags & 16384 || objectFlags & 3) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } - if (type.flags & 16384) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064, false).accessibility === 0) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166, unionTypeNodes); + if (type.flags & (65536 | 131072)) { + var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 ? 166 : 167, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072) { - return ts.createUnionOrIntersectionTypeNode(167, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 | 32)) { ts.Debug.assert(!!(type.flags & 32768)); return createAnonymousTypeNode(type); } if (type.flags & 262144) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -25074,12 +25454,12 @@ var ts; if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455); } else if (ts.contains(context.symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - var entityName = symbolToName(typeAlias, false); + var entityName = symbolToName(typeAlias, context, 793064, false); return ts.createTypeReferenceNode(entityName, undefined); } else { @@ -25121,41 +25501,52 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -25163,7 +25554,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -25173,48 +25564,72 @@ var ts; i++; } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - var qualifiedNamePart = symbolToName(parent, true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, undefined); + qualifiedName = ts.createQualifiedName(namePart, undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); } var properties = resolvedType.properties; if (!properties) { @@ -25223,74 +25638,121 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455, true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 ? ts.createToken(55) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); - var name = ts.getNameFromIndexInfo(indexInfo); - var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); + var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064, true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24), ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 | 16777216); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0, true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -25298,18 +25760,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -25318,20 +25780,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } function getSymbolChain(symbol, meaning, endOfChain) { @@ -25357,28 +25809,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199: + return "(Anonymous class)"; + case 186: + case 187: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -25396,12 +25849,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144)) { if (t.flags & (128 | 256)) { - var baseType = t.flags & 128 ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -25437,13 +25892,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -25486,7 +25942,7 @@ var ts; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { if (flags & 1) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -25551,12 +26007,15 @@ var ts; else if (getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 23); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 && !(type.flags & 65536)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 || type.flags & (16 | 16384)) { + else if (getObjectFlags(type) & 3 || type.flags & (272 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 512) && type.aliasSymbol && @@ -25893,7 +26352,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -26144,10 +26603,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 8388608); } var result = []; if (exportSymbol) { @@ -26268,7 +26724,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -26368,7 +26824,7 @@ var ts; return expr.kind === 177 && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; + return strictNullChecks && optional ? getNullableType(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536) { @@ -26446,6 +26902,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 ? declaration : @@ -26462,16 +26919,23 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536) { - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { @@ -26681,7 +27145,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 ? includeFalsyTypes(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 67108864 ? getNullableType(type, 2048) : type; } } } @@ -26737,7 +27201,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -26913,11 +27377,12 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && areAllOuterTypeParametersApplied(originalBaseType)) { - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; @@ -27081,77 +27546,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 || + return expr.kind === 9 || expr.kind === 8 || expr.kind === 192 && expr.operator === 38 && expr.operand.kind === 8 || - expr.kind === 71 && !!symbol.exports.get(expr.text); + expr.kind === 71 && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 : 1; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 && !(type.flags & 65536) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); + if (enumType_1.flags & 65536) { + enumType_1.flags |= 256; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -27383,7 +27851,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -27460,8 +27928,8 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type = types_2[_i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -27605,7 +28073,7 @@ var ts; var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); @@ -27725,6 +28193,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 ? getConstraintOfTypeParameter(type) : type.flags & 524288 ? getConstraintOfIndexedAccess(type) : @@ -27781,8 +28270,8 @@ var ts; if (t.flags & 196608) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -27824,7 +28313,7 @@ var ts; var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 ? globalStringType : - t.flags & 340 ? globalNumberType : + t.flags & 84 ? globalNumberType : t.flags & 136 ? globalBooleanType : t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : t.flags & 16777216 ? emptyObjectType : @@ -27838,12 +28327,12 @@ var ts; var commonFlags = isUnion ? 0 : 67108864; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -27909,7 +28398,7 @@ var ts; } function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); - return property && !(getCheckFlags(property) & 16) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; } function getPropertyOfType(type, name) { type = getApparentType(type); @@ -28272,8 +28761,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -28400,8 +28890,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -28431,7 +28921,7 @@ var ts; function getTypeReferenceArity(type) { return ts.length(type.target.typeParameters); } - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -28443,7 +28933,7 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -28463,7 +28953,7 @@ var ts; } return instantiation; } - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -28475,7 +28965,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -28512,14 +29001,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 | 64)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 && node.kind === 277) { return getTypeOfSymbol(symbol); @@ -28578,16 +29068,16 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } links.resolvedSymbol = symbol; links.resolvedType = type; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -28809,14 +29299,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -28824,8 +29314,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -28946,8 +29436,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -28998,9 +29488,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -29030,12 +29520,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & (32 | 64 | 256) ? - indexType.text : + var propName = indexType.flags & 96 ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -29050,11 +29540,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 340 | 512)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340) && getIndexInfoOfType(objectType, 1) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || getIndexInfoOfType(objectType, 0) || undefined; if (indexInfo) { @@ -29079,7 +29569,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 | 64)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 | 4)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -29211,7 +29701,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -29228,11 +29718,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 67108864) { + if (rightProp.flags & 67108864) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -29259,15 +29749,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 && !(type.flags & 1048576)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576, type.text); + var freshType = createLiteralType(type.flags | 1048576, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -29278,11 +29769,13 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -29537,7 +30030,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { var links = getSymbolLinks(symbol); symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); @@ -29948,29 +30441,27 @@ var ts; type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 65536) !== (target.flags & 65536)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 128)); } enumRelation.set(id, false); return false; @@ -29981,42 +30472,47 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192) + var s = source.flags; + var t = target.flags; + if (t & 8192) return false; - if (target.flags & 1 || source.flags & 8192) + if (t & 1 || s & 8192) return true; - if (source.flags & 262178 && target.flags & 2) + if (s & 262178 && t & 2) return true; - if (source.flags & 340 && target.flags & 4) + if (s & 32 && s & 256 && + t & 32 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 136 && target.flags & 8) + if (s & 84 && t & 4) return true; - if (source.flags & 256 && target.flags & 16 && source.baseType === target) + if (s & 64 && s & 256 && + t & 64 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 && t & 8) return true; - if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) + if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) + if (s & 256 && t & 256) { + if (s & 65536 && t & 65536 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 && t & 224 && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 && (!strictNullChecks || t & (2048 | 1024))) return true; - if (source.flags & 32768 && target.flags & 16777216) + if (s & 4096 && (!strictNullChecks || t & 4096)) + return true; + if (s & 32768 && t & 16777216) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) + if (s & 1) return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -30200,24 +30696,6 @@ var ts; } return 0; } - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - return true; - } - } - else if (type.flags & 196608) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(source.flags & 33554432); @@ -30566,10 +31044,10 @@ var ts; } } else if (!(targetProp.flags & 16777216)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { - if (getCheckFlags(sourceProp) & 256) { + if (ts.getCheckFlags(sourceProp) & 256) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -30666,23 +31144,34 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } - return 0; } return result; } @@ -30793,7 +31282,7 @@ var ts; } } function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6) { + if (ts.getCheckFlags(prop) & 6) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -30816,11 +31305,11 @@ var ts; }); } function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } function isAbstractConstructorType(type) { @@ -30859,8 +31348,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -30938,8 +31427,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -30947,8 +31436,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -30971,7 +31460,7 @@ var ts; return getUnionType(types, true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -31011,27 +31500,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 | 2048 | 4096)) !== 0; + return (type.flags & (224 | 2048 | 4096)) !== 0; } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 ? stringType : - type.flags & 64 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 ? stringType : + type.flags & 64 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 && type.flags & 1048576 ? stringType : - type.flags & 64 && type.flags & 1048576 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 && type.flags & 1048576 ? stringType : + type.flags & 64 && type.flags & 1048576 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function isTupleType(type) { @@ -31039,43 +31528,43 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; } function getFalsyFlags(type) { return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 ? type.text === "" ? 32 : 0 : - type.flags & 64 ? type.text === "0" ? 64 : 0 : + type.flags & 32 ? type.value === "" ? 32 : 0 : + type.flags & 64 ? type.value === 0 ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : type.flags & 7406; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178) - types.push(emptyStringType); - if (flags & 340) - types.push(zeroType); - if (flags & 136) - types.push(falseType); - if (flags & 1024) - types.push(voidType); - if (flags & 2048) - types.push(undefinedType); - if (flags & 4096) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 ? emptyStringType : + type.flags & 4 ? zeroType : + type.flags & 8 || type === falseType ? falseType : + type.flags & (1024 | 2048 | 4096) || + type.flags & 32 && type.value === "" || + type.flags & 64 && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 | 4096); + return missing === 0 ? type : + missing === 2048 ? getUnionType([type, undefinedType]) : + missing === 4096 ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; } @@ -31220,7 +31709,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { @@ -31297,7 +31786,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -31330,20 +31819,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -31356,7 +31835,7 @@ var ts; } return; } - if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 16 && target.flags & 16) || + if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 256 && target.flags & 256) || source.flags & 131072 && target.flags & 131072) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -31444,26 +31923,25 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + var isNonConstructorObject = target.flags & 32768 && + !(getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -31546,8 +32024,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -31622,7 +32100,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -31632,7 +32110,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99) { return "0"; @@ -31697,7 +32175,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2) { + if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); } @@ -31757,8 +32235,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -31774,15 +32252,16 @@ var ts; return strictNullChecks ? 4079361 : 4194049; } if (flags & 32) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 : 1982209 : - type.text === "" ? 3145473 : 4194049; + isEmpty ? 3030785 : 1982209 : + isEmpty ? 3145473 : 4194049; } if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } - if (flags & (64 | 256)) { - var isZero = type.text === "0"; + if (flags & 64) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 : 1982082 : isZero ? 3145346 : 4193922; @@ -31984,7 +32463,7 @@ var ts; } return true; } - if (source.flags & 256 && target.flags & 16 && source.baseType === target) { + if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -32007,8 +32486,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -32077,8 +32556,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -32104,7 +32583,7 @@ var ts; parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 | 2048); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -32130,7 +32609,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -32250,7 +32729,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | 2048)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -32683,6 +33162,22 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 || + parent.kind === 181 && parent.expression === node || + parent.kind === 180 && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144); + } + function getDeclaredOrApparentType(symbol, node) { + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -32737,7 +33232,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -32767,12 +33262,12 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048); + getNullableType(type, 2048); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -33467,8 +33962,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -33559,7 +34054,7 @@ var ts; return name.kind === 144 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -33574,7 +34069,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 262178 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 | 262178 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -33712,6 +34207,8 @@ var ts; } if (spread.flags & 32768) { spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; spread.symbol = node.symbol; } return spread; @@ -33771,6 +34268,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -33788,6 +34289,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255); @@ -33797,37 +34301,37 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; if (child.kind === 10) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); @@ -33837,9 +34341,8 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } var childrenPropSymbol = createSymbol(4 | 134217728, jsxChildrenPropertyName); @@ -33849,11 +34352,15 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, undefined, undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 33554432 | 4194304 | freshObjectLiteralFlag; + result.flags |= 33554432 | 4194304; result.objectFlags |= 128; return result; } @@ -33908,7 +34415,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -33942,6 +34460,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 65536)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { @@ -33951,6 +34483,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { @@ -33976,6 +34509,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -34021,7 +34555,7 @@ var ts; else if (elementType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -34179,6 +34713,24 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + return true; + } + } + else if (targetType.flags & 196608) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : @@ -34190,7 +34742,16 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -34208,36 +34769,18 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 ? flags : flags & ~28; - } - if (getCheckFlags(s) & 6) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 ? 8 : - checkFlags & 64 ? 4 : - 16; - var staticModifier = checkFlags & 512 ? 32 : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216) { - return 4 | 32; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || getCheckFlags(symbol) & 4); + return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); } function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 || node.kind === 226 ? node.name : node.right; - if (getCheckFlags(prop) & 256) { + if (ts.getCheckFlags(prop) & 256) { error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } @@ -34312,42 +34855,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 && !(containingType.flags & 8190)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (getCheckFlags(prop) & 1) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -34383,7 +34890,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -34399,6 +34906,107 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + if (ts.getCheckFlags(prop) & 1) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 ? node.expression @@ -34506,7 +35114,13 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183) { checkExpression(node.template); } @@ -34529,8 +35143,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -34617,7 +35231,7 @@ var ts; return false; } if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } if (!signature.hasRestParameter && argCount > signature.parameters.length) { return false; @@ -34853,7 +35467,7 @@ var ts; case 71: case 8: case 9: - return getLiteralTypeForText(32, element.name.text); + return getLiteralType(element.name.text); case 144: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512)) { @@ -34931,7 +35545,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183; var isDecorator = node.kind === 147; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -34959,7 +35573,7 @@ var ts; var candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -35000,25 +35614,56 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -35028,14 +35673,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -35166,7 +35803,7 @@ var ts; } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } if (isTypeAny(expressionType)) { @@ -35293,8 +35930,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -35438,7 +36075,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048); + return getNullableType(type, 2048); } } return type; @@ -35502,10 +36139,10 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 || - parameter.valueDeclaration.name.kind === 175)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -35789,15 +36426,15 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { error(operand, diagnostic); return false; } return true; } function isReadonlySymbol(symbol) { - return !!(getCheckFlags(symbol) & 8 || - symbol.flags & 4 && getDeclarationModifierFlagsFromSymbol(symbol) & 64 || + return !!(ts.getCheckFlags(symbol) & 8 || + symbol.flags & 4 && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 || symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || symbol.flags & 98304 && !(symbol.flags & 65536) || symbol.flags & 8); @@ -35877,7 +36514,7 @@ var ts; return silentNeverType; } if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37: @@ -35920,8 +36557,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -35935,8 +36572,8 @@ var ts; } if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -35945,8 +36582,8 @@ var ts; } if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -35981,7 +36618,7 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 | 512))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { @@ -36253,7 +36890,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { + if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { resultType = numberType; } else { @@ -36307,7 +36944,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53: return getTypeFacts(leftType) & 1048576 ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54: return getTypeFacts(leftType) & 2097152 ? @@ -36389,12 +37026,12 @@ var ts; var func = ts.getContainingFunction(node); var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 4096); - } + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256); } } @@ -36434,9 +37071,9 @@ var ts; } switch (node.kind) { case 9: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: return trueType; case 86: @@ -36490,7 +37127,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 | 262144)); + return maybeTypeOfKind(contextualType, (224 | 262144)); } return false; } @@ -36787,17 +37424,14 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - if (languageVersion < 2) { - checkExternalEmitHelpers(node, 128); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); } - } - if ((functionFlags & 5) === 1) { - if (functionFlags & 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 2048); + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); } - else if (languageVersion < 2) { + if ((functionFlags & 3) !== 0 && languageVersion < 2) { checkExternalEmitHelpers(node, 128); } } @@ -36820,7 +37454,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5) === 1) { + if ((functionFlags_1 & (4 | 1)) === 1) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -36941,7 +37575,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -37015,7 +37649,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -37153,7 +37788,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { + if (type.flags & 16 && getNodeLinks(node).resolvedSymbol.flags & 8) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -37192,7 +37827,7 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 340)) { + if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1)) { return type; @@ -37242,16 +37877,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 | 16)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -37262,7 +37897,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -37370,7 +38005,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && @@ -37383,8 +38018,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -37433,11 +38068,12 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -37633,7 +38269,9 @@ var ts; checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 ? 793064 : 1920) | 8388608, undefined, undefined); if (rootSymbol @@ -37643,6 +38281,43 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167: + case 166: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + return undefined; + } + if (commonEntityName) { + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168: + return getEntityNameForDecoratorMetadata(node.type); + case 159: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -37669,7 +38344,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -37678,15 +38353,15 @@ var ts; case 154: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -37799,15 +38474,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -37885,7 +38561,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -37947,7 +38623,7 @@ var ts; if (getNodeCheckFlags(current) & 4) { var isDeclaration_1 = node.kind !== 71; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -37961,7 +38637,7 @@ var ts; if (getNodeCheckFlags(current) & 8) { var isDeclaration_2 = node.kind !== 71; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -38157,7 +38833,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -38263,11 +38939,12 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216) { if (node.awaitModifier) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 8192); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); } } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } } @@ -38717,11 +39394,14 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -38936,7 +39616,7 @@ var ts; } } function getTargetSymbol(s) { - return getCheckFlags(s) & 1 ? s.target : s; + return ts.getCheckFlags(s) & 1 ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -38955,7 +39635,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { @@ -38970,13 +39650,10 @@ var ts; } } else { - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { continue; } - if ((baseDeclarationFlags & 32) !== (derivedDeclarationFlags & 32)) { - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { continue; } @@ -38995,7 +39672,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -39078,88 +39755,81 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); + nodeLinks.flags |= 16384; var autoValue = 0; - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37: return value_1; case 38: return -value_1; case 52: return ~value_1; } - return undefined; - case 194: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49: return left | right; case 48: return left & right; case 46: return left >> right; @@ -39172,75 +39842,53 @@ var ts; case 38: return left - right; case 42: return left % right; } - return undefined; - case 8: - checkGrammarNumericLiteral(e); - return +e.text; - case 185: - return evalConstant(e.expression); - case 71: - case 180: - case 179: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71) { - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9: + return expr.text; + case 8: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185: + return evaluate(expr.expression); + case 71: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180: + case 179: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384) { + var name = expr.kind === 179 ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - var current = expression; - while (current) { - if (current.kind === 71) { - break; - } - else if (current.kind === 179) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - if (member === propertyDecl) { - return undefined; - } - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return 0; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 || + node.kind === 179 && isConstantMemberAccess(node.expression) || + node.kind === 180 && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -39263,7 +39911,7 @@ var ts; if (enumSymbol.declarations.length > 1) { ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -39488,6 +40136,9 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + if (node.kind === 246 && compilerOptions.isolatedModules && !(target.flags & 107455)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -40134,7 +40785,7 @@ var ts; if (isInsideWithStatementBody(node)) { return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { return getSymbolOfNode(node.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { @@ -40247,7 +40898,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -40309,16 +40960,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728) { if (symbol.leftSpread) { @@ -40579,7 +41230,7 @@ var ts; else if (isTypeOfKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340)) { + else if (isTypeOfKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178)) { @@ -40607,7 +41258,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -40619,15 +41270,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -40706,7 +41348,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -40853,7 +41494,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 8192; helper <<= 1) { + for (var helper = 1; helper <= 16384; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); @@ -40880,9 +41521,10 @@ var ts; case 256: return "__values"; case 512: return "__read"; case 1024: return "__spread"; - case 2048: return "__asyncGenerator"; - case 4096: return "__asyncDelegator"; - case 8192: return "__asyncValues"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -41911,6 +42553,17 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242: + case 246: + if (name.parent.propertyName) { + return true; + } + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -42021,49 +42674,59 @@ var ts; if ((kind > 0 && kind <= 142) || kind === 169) { return node; } - switch (node.kind) { - case 206: - case 209: - case 200: - case 225: - case 298: - case 247: - return node; + switch (kind) { + case 71: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - case 160: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 145: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); - case 159: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 148: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 158: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170: @@ -42074,20 +42737,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - case 145: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 148: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 174: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 175: @@ -42124,12 +42773,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196: @@ -42146,6 +42795,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); case 205: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 207: @@ -42190,6 +42841,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233: @@ -42198,6 +42853,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238: @@ -42222,8 +42879,6 @@ var ts; return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 249: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251: @@ -42232,6 +42887,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256: @@ -42256,6 +42913,8 @@ var ts; return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); case 296: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; } @@ -42311,6 +42970,13 @@ var ts; case 147: result = reduceNode(node.expression, cbNode, result); break; + case 148: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -42649,6 +43315,9 @@ var ts; case 296: result = reduceNode(node.expression, cbNode, result); break; + case 297: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -43099,7 +43768,7 @@ var ts; var applicableSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -43888,15 +44557,10 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || serializedUnion.text !== serializedIndividual.text) { @@ -44183,7 +44847,12 @@ var ts; } function transformEnumMember(member) { var name = getExpressionForPropertyName(member, false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } function transformEnumMemberDeclarationValue(member) { var value = resolver.getConstantValue(member); @@ -44230,9 +44899,9 @@ var ts; return false; } function addVarForEnumOrModuleDeclaration(statements, node) { - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, false, true)) - ]); + ], currentScope.kind === 265 ? 0 : 1)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -44365,7 +45034,7 @@ var ts; } function visitExportDeclaration(node) { if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { return undefined; @@ -44675,7 +45344,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -44920,7 +45589,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -44988,19 +45657,14 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), node), node); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -45127,6 +45791,9 @@ var ts; } return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); } + function awaitAsYield(expression) { + return ts.createYield(undefined, enclosingFunctionFlags & 1 ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); @@ -45134,19 +45801,17 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(undefined); - var values = createAsyncValuesHelper(context, expression, node.expression); - var next = ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), - ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), node), 256); + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, awaitAsYield(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -45155,12 +45820,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -45392,12 +46052,22 @@ var ts; return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ @@ -45409,11 +46079,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); } var asyncValues = { @@ -45432,7 +46102,7 @@ var ts; var compilerOptions = context.getCompilerOptions(); return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -45870,7 +46540,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -46012,7 +46682,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -46875,12 +47545,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { updated = undefined; @@ -47768,7 +48439,7 @@ var ts; if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -47936,8 +48607,7 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; } currentSourceFile = node; @@ -49623,7 +50293,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -49786,9 +50456,9 @@ var ts; return visitFunctionDeclaration(node); case 229: return visitClassDeclaration(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return node; @@ -50292,9 +50962,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -50807,9 +51475,9 @@ var ts; return visitCatchClause(node); case 207: return visitBlock(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -51100,7 +51768,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -51215,7 +51883,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299); + var enabledSyntaxKindFeatures = new Array(300); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -51273,7 +51941,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } function enableSubstitution(kind) { ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); @@ -51443,7 +52111,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencesOutput = ""; @@ -51468,11 +52136,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -51876,8 +52544,7 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -51890,23 +52557,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -51916,12 +52590,6 @@ var ts; var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -51991,7 +52659,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && !noDeclare) { + else if (node.kind !== 230 && needsDeclare) { write("declare "); } } @@ -52219,7 +52887,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -52316,7 +52984,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -52328,12 +52996,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 229) { @@ -52347,7 +53009,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -52362,6 +53024,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128)) { @@ -52369,15 +53044,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); write(" {"); writeLine(); increaseIndent(); @@ -52398,7 +53080,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, false); + emitHeritageClause(interfaceExtendsTypes, false); } write(" {"); writeLine(); @@ -52450,7 +53132,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 || node.kind === 148) { + else if (node.kind === 149 || node.kind === 148 || + (node.kind === 146 && ts.hasModifier(node.parent, 8))) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -52458,7 +53141,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 229 || node.kind === 146) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -52653,6 +53336,11 @@ var ts; write("["); } else { + if (node.kind === 152 && ts.hasModifier(node, 8)) { + write("();"); + writeLine(); + return; + } if (node.kind === 156 || node.kind === 161) { write("new "); } @@ -52911,7 +53599,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { declFileName = referencedFile.fileName; } else { @@ -53674,7 +54362,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -53705,7 +54393,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -53791,7 +54479,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -53867,7 +54557,7 @@ var ts; function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -54067,7 +54757,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -54087,7 +54777,7 @@ var ts; case 97: case 101: case 99: - writeTokenText(kind); + writeTokenNode(node); return; case 177: return emitArrayLiteralExpression(node); @@ -54149,6 +54839,8 @@ var ts; return emitJsxSelfClosingElement(node); case 296: return emitPartiallyEmittedExpression(node); + case 297: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -54174,6 +54866,7 @@ var ts; } function emitIdentifier(node) { write(getTextOfNode(node, false)); + emitTypeArguments(node, node.typeArguments); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -54196,6 +54889,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -54310,7 +55004,9 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65); + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 ? 448 : 65); + } write("}"); } function emitArrayType(node) { @@ -54348,9 +55044,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -54361,8 +55063,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -54375,7 +55082,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432); + emitList(node, elements, ts.getEmitFlags(node) & 1 ? 272 : 432); write("}"); } } @@ -54451,7 +55158,7 @@ var ts; } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -54542,7 +55249,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -55221,6 +55928,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272); + } function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { for (var i = 0; i < statements.length; i++) { var statement = statements[i]; @@ -55469,6 +56179,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -55646,7 +56365,9 @@ var ts; if (node.kind === 9 && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -55860,14 +56581,17 @@ var ts; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; @@ -56081,6 +56805,83 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); + lineContent = lineContent.replace("\t", " "); + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -56130,6 +56931,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -56172,7 +56974,8 @@ var ts; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); if (typeReferences.length) { @@ -56221,7 +57024,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -56254,45 +57058,64 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { + if (structuralIsReused === 0 && !file.ambientModuleNames.length) { return resolveModuleNamesWorker(moduleNames, containingFile); } + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } var unknownModuleNames; var result; var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - var isKnownToResolveToAmbientModule = false; + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - result = new Array(moduleNames.length); - unknownModuleNames = moduleNames.slice(0, i); - } - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - unknownModuleNames.push(moduleName); + else { + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; + if (!result) { + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -56301,15 +57124,12 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -56328,67 +57148,73 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0; } var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 | 1))); var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0; } var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - newSourceFile = oldSourceFile; - } newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -56396,11 +57222,16 @@ var ts; var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; } for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); @@ -56412,8 +57243,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { return { @@ -56753,7 +57583,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -56784,7 +57614,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -56825,13 +57654,13 @@ var ts; } break; case 233: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { (ambientModules || (ambientModules = [])).push(moduleName.text); } var body = node.body; @@ -56854,45 +57683,50 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -57028,10 +57862,10 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -57080,7 +57914,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -57177,12 +58011,12 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -57509,7 +58343,6 @@ var ts; case 148: case 261: case 262: - case 264: case 151: case 150: case 152: @@ -57526,9 +58359,11 @@ var ts; case 231: case 163: return 2; + case 264: case 229: - case 232: return 1 | 2; + case 232: + return 7; case 233: if (ts.isAmbientModule(node)) { return 4 | 1; @@ -57545,7 +58380,7 @@ var ts; case 238: case 243: case 244: - return 1 | 2 | 4; + return 7; case 265: return 4 | 1; } @@ -57700,7 +58535,7 @@ var ts; case 153: case 154: case 233: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180: return node.parent.argumentExpression === node; case 144: @@ -57715,31 +58550,6 @@ var ts; ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; - function isInsideComment(sourceFile, token, position) { - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47) { - return true; - } - else { - return !(text.charCodeAt(comment.end - 1) === 47 && - text.charCodeAt(comment.end - 2) === 42); - } - } - return false; - }); - } - } - ts.isInsideComment = isInsideComment; function getContainerNode(node) { while (true) { node = node.parent; @@ -58045,43 +58855,24 @@ var ts; if (ts.isToken(current)) { return current; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } - for (var _a = 0, _b = current.getChildren(); _a < _b.length; _a++) { - var child = _b[_a]; - if (ts.isJSDocNode(child)) { + for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + if (ts.isJSDocNode(child) && !includeJsDocComment) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + continue; + } + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } @@ -58175,10 +58966,6 @@ var ts; return false; } ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, undefined); - } - ts.isInComment = isInComment; function isInsideJsxElementOrAttribute(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); if (!token) { @@ -58207,20 +58994,29 @@ var ts; return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 ? position <= c.end : position < c.end); }); + function isInComment(sourceFile, position, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position); } + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); + function isInCommentRange(commentRanges) { + return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); + } + } + ts.isInComment = isInComment; + function isPositionInCommentRange(_a, position, text) { + var pos = _a.pos, end = _a.end, kind = _a.kind; + if (pos < position && position < end) { + return true; + } + else if (position === end) { + return kind === 2 || + !(text.charCodeAt(end - 1) === 47 && text.charCodeAt(end - 2) === 42); + } + else { + return false; } - return false; } - ts.isInCommentHelper = isInCommentHelper; function hasDocComment(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); @@ -58336,6 +59132,9 @@ var ts; } ts.isAccessibilityModifier = isAccessibilityModifier; function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } for (var e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { @@ -58376,25 +59175,27 @@ var ts; } ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { + return isInComment(sourceFile, position, undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { + return isInComment(sourceFile, position, undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInNonReferenceComment = isInNonReferenceComment; function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; function isTypeKeyword(kind) { switch (kind) { case 119: @@ -58654,8 +59455,8 @@ var ts; }; var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; diagnostic.start = diagnostic.start - 1; } var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; @@ -59202,7 +60003,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -59210,8 +60011,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -60070,8 +60871,8 @@ var ts; continue; } var start = completePrefix.length; - var length_6 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_6))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -60328,7 +61129,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; if (requestJsDocTagName) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; } @@ -60352,13 +61153,16 @@ var ts; sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); } - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + if (hasFilteredClassMemberKeywords) { + ts.addRange(entries, classMemberKeywordCompletions); + } + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; @@ -60403,8 +61207,8 @@ var ts; var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { + var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -60461,10 +61265,11 @@ var ts; function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) { var candidates = []; var entries = []; + var uniques = ts.createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { var candidate = candidates_3[_i]; - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; @@ -60492,9 +61297,10 @@ var ts; } return undefined; } - function addStringLiteralCompletionsFromType(type, result, typeChecker) { + function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 16384) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; @@ -60502,16 +61308,20 @@ var ts; if (type.flags & 65536) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & 32) { - result.push({ - name: type.text, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, - sortText: "0" - }); + var name = type.value; + if (!uniques.has(name)) { + uniques.set(name, true); + result.push({ + name: name, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } } } function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { @@ -60562,7 +61372,7 @@ var ts; var currentToken = ts.getTokenAtPosition(sourceFile, position); log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); - var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { @@ -60592,7 +61402,7 @@ var ts; } } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -60663,6 +61473,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; + var hasFilteredClassMemberKeywords = false; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -60693,7 +61504,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols() { isGlobalCompletion = false; isMemberCompletion = true; @@ -60735,6 +61546,7 @@ var ts; function tryGetGlobalSymbols() { var objectLikeContainer; var namedImportsOrExports; + var classLikeContainer; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); @@ -60742,6 +61554,10 @@ var ts; if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; + } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; if ((jsxContainer.kind === 250) || (jsxContainer.kind === 251)) { @@ -60871,12 +61687,14 @@ var ts; } function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { isMemberCompletion = true; - var typeForObject; + var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178) { isNewIdentifierLocation = true; - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 174) { @@ -60893,7 +61711,10 @@ var ts; } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = objectLikeContainer.elements; } } @@ -60904,10 +61725,6 @@ var ts; else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { symbols = filterObjectMembersList(typeMembers, existingMembers); } @@ -60933,6 +61750,42 @@ var ts; symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); return true; } + function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + isMemberCompletion = true; + isNewIdentifierLocation = true; + hasFilteredClassMemberKeywords = true; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); + var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + if (contextToken.kind === 71 && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32; + break; + } + } + if (!(classElementModifierFlags & 8)) { + var baseClassTypeToGetPropertiesFrom = void 0; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & 32) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32) ? + undefined : + ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + } + } + } function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { @@ -60961,6 +61814,37 @@ var ts; } return undefined; } + function isFromClassElementDeclaration(node) { + return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); + } + function tryGetClassLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 17: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + case 26: + case 25: + case 18: + if (ts.isClassLike(location)) { + return location; + } + break; + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent; + } + } + } + if (location && location.kind === 294 && ts.isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -61050,7 +61934,7 @@ var ts; containingNodeKind === 231 || isFunction(containingNodeKind); case 115: - return containingNodeKind === 149; + return containingNodeKind === 149 && !ts.isClassLike(contextToken.parent.parent); case 24: return containingNodeKind === 146 || (contextToken.parent && contextToken.parent.parent && @@ -61063,13 +61947,16 @@ var ts; return containingNodeKind === 242 || containingNodeKind === 246 || containingNodeKind === 240; + case 125: + case 135: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } case 75: case 83: case 109: case 89: case 104: - case 125: - case 135: case 91: case 110: case 76: @@ -61077,6 +61964,10 @@ var ts; case 138: return true; } + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } switch (contextToken.getText()) { case "abstract": case "async": @@ -61108,7 +61999,7 @@ var ts; var existingImportsOrExports = ts.createMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; @@ -61134,7 +62025,7 @@ var ts; m.kind !== 154) { continue; } - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; @@ -61144,17 +62035,51 @@ var ts; } } else { - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); } + function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + if (m.kind !== 149 && + m.kind !== 151 && + m.kind !== 153 && + m.kind !== 154) { + continue; + } + if (isCurrentlyEditingNode(m)) { + continue; + } + if (ts.hasModifier(m, 8)) { + continue; + } + var mIsStatic = ts.hasModifier(m, 32); + var currentElementIsStatic = !!(currentClassElementModifierFlags & 32); + if ((mIsStatic && !currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return ts.concatenate(ts.filter(baseSymbols, function (baseProperty) { return isValidProperty(baseProperty, 8); }), ts.filter(implementingTypeSymbols, function (implementingProperty) { return isValidProperty(implementingProperty, 24); })); + function isValidProperty(propertySymbol, inValidModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } + } function filterJsxAttributes(symbols, attributes) { var seenNames = ts.createMap(); for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253) { @@ -61163,6 +62088,9 @@ var ts; } return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); } + function isCurrentlyEditingNode(node) { + return node.getStart() <= position && position <= node.getEnd(); + } } function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { var displayName = ts.getDeclaredName(typeChecker, symbol, location); @@ -61198,6 +62126,27 @@ var ts; sortText: "0" }); } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 114: + case 113: + case 112: + case 117: + case 115: + case 123: + case 131: + case 125: + case 135: + case 120: + return true; + } + } + function isClassMemberCompletionKeywordText(text) { + return isClassMemberCompletionKeyword(ts.stringToToken(text)); + } + var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { + return isClassMemberCompletionKeywordText(entry.name); + }); function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -61213,9 +62162,9 @@ var ts; (function (ts) { var DocumentHighlights; (function (DocumentHighlights) { - function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) { + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -61227,8 +62176,8 @@ var ts; kind: ts.HighlightSpanKind.none }; } - function getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -61954,6 +62903,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240) { @@ -62019,10 +62971,41 @@ var ts; } }); } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 265) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -62044,7 +63027,7 @@ var ts; }); } function forEachImport(sourceFile, action) { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); @@ -62072,25 +63055,20 @@ var ts; } } }); - if (sourceFile.flags & 65536) { - sourceFile.forEachChild(function recur(node) { - if (ts.isRequireCall(node, true)) { - action(node, node.arguments[0]); - } - else { - node.forEachChild(recur); - } - }); - } } } function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; - if (decl.kind === 238 || decl.kind === 244) { - return decl; + switch (decl.kind) { + case 181: + case 238: + case 244: + return decl; + case 248: + return decl.parent; + default: + ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); } - ts.Debug.assert(decl.kind === 248); - return decl.parent; } function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { return comingFromExport ? getExport() : getExport() || getImport(); @@ -62209,12 +63187,13 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + return ts.forEach(symbol.declarations, function (decl) { + if (ts.isExportAssignment(decl)) { + return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + } + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 && name.text; }); - ts.Debug.assert(!!name); - return name; } function skipExportSpecifierSymbol(symbol, checker) { if (symbol.declarations) @@ -62257,12 +63236,13 @@ var ts; return { type: "node", node: node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; - function findReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } var out = []; + var checker = program.getTypeChecker(); for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; if (definition) { @@ -62272,39 +63252,41 @@ var ts; return out; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; - function getImplementationsAtPosition(checker, cancellationToken, sourceFiles, sourceFile, position) { + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(typeChecker, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + var checker = program.getTypeChecker(); if (node.parent.kind === 262) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 || ts.isSuperProperty(node.parent)) { - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(checker, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { + var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options) { + function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -62314,10 +63296,6 @@ var ts; switch (def.type) { case "symbol": { var symbol = def.symbol, node_2 = def.node; - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; @@ -62454,7 +63432,7 @@ var ts; (function (FindAllReferences) { var Core; (function (Core) { - function getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } if (node.kind === 265) { return undefined; @@ -62465,6 +63443,7 @@ var ts; return special; } } + var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); if (!symbol) { if (!options.implementations && node.kind === 9) { @@ -62472,12 +63451,59 @@ var ts; } return undefined; } - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; + if (symbol.flags & 1536 && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleReferenceLocation(node) { + if (node.kind !== 9) { + return false; + } + switch (node.parent.kind) { + case 233: + case 248: + case 238: + case 244: + return true; + case 181: + return ts.isRequireCall(node.parent, false); + default: + return false; + } + } + function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 265: + break; + case 233: + references.push({ type: "node", node: decl.name }); + break; + default: + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + return [{ + definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, + references: references + }]; + } function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken); @@ -62672,7 +63698,11 @@ var ts; } return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + if (container === void 0) { container = sourceFile; } + if (fullStart === void 0) { fullStart = false; } + var start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + var end = container.getEnd(); var positions = []; if (!symbolName || !symbolName.length) { return positions; @@ -62697,15 +63727,11 @@ var ts; var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { var position = possiblePositions_1[_i]; var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } - if (node === targetLabel || - (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } } @@ -62714,27 +63740,27 @@ var ts; function isValidReferencePosition(node, searchSymbolName) { switch (node && node.kind) { case 71: - return node.getWidth() === searchSymbolName.length; + return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; case 9: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - node.getWidth() === searchSymbolName.length + 2; + node.text.length === searchSymbolName.length; case 8: - return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; default: return false; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); @@ -62751,10 +63777,8 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - var start = state.findInComments ? container.getFullStart() : container.getStart(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, state.findInComments); _i < _a.length; _i++) { + var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } @@ -62862,7 +63886,7 @@ var ts; var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); if (!(flags & 134217728) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -63092,9 +64116,9 @@ var ts; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { - var position = possiblePositions_4[_i]; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); + for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { + var position = possiblePositions_3[_i]; var node = ts.getTouchingWord(sourceFile, position); if (!node || node.kind !== 97) { continue; @@ -63138,13 +64162,13 @@ var ts; if (searchSpaceNode.kind === 265) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ @@ -63188,10 +64212,10 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } return [{ @@ -63199,8 +64223,8 @@ var ts; references: references }]; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { - for (var _i = 0, possiblePositions_5 = possiblePositions; _i < possiblePositions_5.length; _i++) { - var position = possiblePositions_5[_i]; + for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { + var position = possiblePositions_4[_i]; var node_7 = ts.getTouchingWord(sourceFile, position); if (node_7 && node_7.kind === 9 && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, true)); @@ -63329,20 +64353,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_5 = []; + var result_6 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -63481,12 +64505,10 @@ var ts; if (!symbol) { return undefined; } - if (symbol.flags & 8388608) { - var declaration = symbol.declarations[0]; - if (node.kind === 71 && - (node.parent === declaration || - (declaration.kind === 242 && declaration.parent && declaration.parent.kind === 241))) { - symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.flags & 8388608 && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; } } if (node.parent.kind === 262) { @@ -63500,21 +64522,11 @@ var ts; var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } - if (ts.isJsxOpeningLikeElement(node.parent)) { - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } var element = ts.getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent)) { - var result = []; - var propertySymbols = ts.getPropertySymbolsFromContextualType(typeChecker, element); - for (var _i = 0, propertySymbols_1 = propertySymbols; _i < propertySymbols_1.length; _i++) { - var propertySymbol = propertySymbols_1[_i]; - result.push.apply(result, getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent)) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); } return getDefinitionFromSymbol(typeChecker, symbol, node); } @@ -63533,13 +64545,13 @@ var ts; return undefined; } if (type.flags & 65536 && !(type.flags & 16)) { - var result_6 = []; + var result_7 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_6, getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(result_7, getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_6; + return result_7; } if (!type.symbol) { return undefined; @@ -63547,6 +64559,23 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function shouldSkipAlias(node, declaration) { + if (node.kind !== 71) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 239: + case 237: + return true; + case 242: + return declaration.parent.kind === 241; + default: + return false; + } + } function getDefinitionFromSymbol(typeChecker, symbol, node) { var result = []; var declarations = symbol.getDeclarations(); @@ -63611,7 +64640,7 @@ var ts; } } function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { var sourceFile = name.getSourceFile(); @@ -63638,7 +64667,7 @@ var ts; function findReferenceInPosition(refs, pos) { for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } @@ -63707,6 +64736,7 @@ var ts; "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -63717,8 +64747,6 @@ var ts; "throws", "type", "typedef", - "property", - "prop", "version" ]; var jsDocTagNameCompletionEntries; @@ -64092,8 +65120,8 @@ var ts; } }); }; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_4(sourceFile); } rawItems = ts.filter(rawItems, function (item) { @@ -64134,16 +65162,19 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144) { - return tryAddComputedPropertyName(declaration.name.expression, containers, true); - } - else { - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144) { + return tryAddComputedPropertyName(name.expression, containers, true); + } + else { + return false; + } } } return true; @@ -64167,8 +65198,9 @@ var ts; } function getContainers(declaration) { var containers = []; - if (declaration.name.kind === 144) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144) { + if (!tryAddComputedPropertyName(name.expression, containers, false)) { return undefined; } } @@ -64201,6 +65233,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -64209,8 +65242,8 @@ var ts; isCaseSensitive: rawItem.isCaseSensitive, fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -64424,8 +65457,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { return true; } @@ -64503,9 +65536,9 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186: @@ -64522,7 +65555,7 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -65742,7 +66775,7 @@ var ts; } } function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (node.parent.kind === 181 || node.parent.kind === 182) { + if (ts.isCallOrNewExpression(node.parent)) { var callExpression = node.parent; if (node.kind === 27 || node.kind === 19) { @@ -66120,7 +67153,7 @@ var ts; } } var callExpressionLike = void 0; - if (location.kind === 181 || location.kind === 182) { + if (ts.isCallOrNewExpression(location)) { callExpressionLike = location; } else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { @@ -66185,24 +67218,29 @@ var ts; } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || (location.kind === 123 && location.parent.kind === 152)) { - var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); - if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); + var functionDeclaration_1 = location.parent; + var locationIsSymbolDeclaration = ts.findDeclaration(symbol, function (declaration) { + return declaration === (location.kind === 123 ? functionDeclaration_1.parent : functionDeclaration_1); + }); + if (locationIsSymbolDeclaration) { + var allSignatures = functionDeclaration_1.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration_1.kind === 152) { + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 && + !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; } - else { - signature = allSignatures[0]; - } - if (functionDeclaration.kind === 152) { - symbolKind = ts.ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 155 && - !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; } } } @@ -66266,9 +67304,9 @@ var ts; writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - var declaration = ts.getDeclarationOfKind(symbol, 145); - ts.Debug.assert(declaration !== undefined); - declaration = declaration.parent; + var decl = ts.getDeclarationOfKind(symbol, 145); + ts.Debug.assert(decl !== undefined); + var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); @@ -66302,7 +67340,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58)); displayParts.push(ts.spacePart()); - displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); } } } @@ -66548,7 +67586,7 @@ var ts; ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); ts.addRange(diagnostics, program.getOptionsDiagnostics()); } - program.emit(); + program.emit(undefined, undefined, undefined, undefined, transpileOptions.transformers); ts.Debug.assert(outputText !== undefined, "Output generation failed"); return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } @@ -66822,9 +67860,10 @@ var ts; var formatting; (function (formatting) { var FormattingContext = (function () { - function FormattingContext(sourceFile, formattingRequestKind) { + function FormattingContext(sourceFile, formattingRequestKind, options) { this.sourceFile = sourceFile; this.formattingRequestKind = formattingRequestKind; + this.options = options; } FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); @@ -67062,7 +68101,7 @@ var ts; this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.FromTokens([22, 26, 25])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyExcept(120), 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(22, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); @@ -67070,10 +68109,10 @@ var ts; this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([20, 3, 81, 102, 87, 82]); this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); + this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); @@ -67090,11 +68129,12 @@ var ts; this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(38, 44), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 26), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([104, 100, 94, 80, 96, 103, 121]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterNewKeywordOnConstructorSignature = new formatting.Rule(formatting.RuleDescriptor.create1(94, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConstructorSignatureContext), 8)); this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([110, 76]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(89, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); + this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(105, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(96, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([20, 81, 82, 73]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); @@ -67102,8 +68142,8 @@ var ts; this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125, 135]), 71), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([128, 132]), 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([117, 75, 124, 79, 83, 84, 85, 125, 108, 91, 109, 128, 129, 112, 114, 113, 131, 135, 115, 138, 140, 127]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([85, 108, 140])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); @@ -67134,6 +68174,41 @@ var ts; this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 58), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(58, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBeforeNonNullAssertionOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 51), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonNullAssertionContext), 8)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); + this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 2)); + this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 8)); + this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 2)); + this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 8)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, @@ -67177,7 +68252,25 @@ var ts; this.SpaceBeforeAt, this.NoSpaceAfterAt, this.SpaceAfterDecorator, - this.NoSpaceBeforeNonNullAssertionOperator + this.NoSpaceBeforeNonNullAssertionOperator, + this.NoSpaceAfterNewKeywordOnConstructorSignature + ]; + this.UserConfigurableRules = [ + this.SpaceAfterConstructor, this.NoSpaceAfterConstructor, + this.SpaceAfterComma, this.NoSpaceAfterComma, + this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, + this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, + this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, + this.SpaceAfterOpenBracket, this.SpaceBeforeCloseBracket, this.NoSpaceBetweenBrackets, this.NoSpaceAfterOpenBracket, this.NoSpaceBeforeCloseBracket, + this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceAfterOpenBrace, this.NoSpaceBeforeCloseBrace, + this.SpaceAfterTemplateHeadAndMiddle, this.SpaceBeforeTemplateMiddleAndTail, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, + this.SpaceAfterOpenBraceInJsxExpression, this.SpaceBeforeCloseBraceInJsxExpression, this.NoSpaceAfterOpenBraceInJsxExpression, this.NoSpaceBeforeCloseBraceInJsxExpression, + this.SpaceAfterSemicolonInFor, this.NoSpaceAfterSemicolonInFor, + this.SpaceBeforeBinaryOperator, this.SpaceAfterBinaryOperator, this.NoSpaceBeforeBinaryOperator, this.NoSpaceAfterBinaryOperator, + this.SpaceBeforeOpenParenInFuncDecl, this.NoSpaceBeforeOpenParenInFuncDecl, + this.NewLineBeforeOpenBraceInControl, + this.NewLineBeforeOpenBraceInFunction, this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock, + this.SpaceAfterTypeAssertion, this.NoSpaceAfterTypeAssertion ]; this.LowPriorityCommonRules = [ this.NoSpaceBeforeSemicolon, @@ -67188,41 +68281,6 @@ var ts; this.SpaceAfterSemicolon, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); - this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8)); - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); } Rules.prototype.getRuleName = function (rule) { var o = this; @@ -67233,6 +68291,18 @@ var ts; } throw new Error("Unknown rule"); }; + Rules.IsOptionEnabled = function (optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + }; + Rules.IsOptionDisabled = function (optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + }; + Rules.IsOptionDisabledOrUndefined = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + }; + Rules.IsOptionEnabledOrUndefined = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + }; Rules.IsForContext = function (context) { return context.contextNode.kind === 214; }; @@ -67448,6 +68518,9 @@ var ts; Rules.IsObjectTypeContext = function (context) { return context.contextNode.kind === 163; }; + Rules.IsConstructorSignatureContext = function (context) { + return context.contextNode.kind === 156; + }; Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { if (token.kind !== 27 && token.kind !== 29) { return false; @@ -67529,8 +68602,7 @@ var ts; }; RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { var _this = this; - var specificRule = rule.Descriptor.LeftTokenRange !== formatting.Shared.TokenRange.Any && - rule.Descriptor.RightTokenRange !== formatting.Shared.TokenRange.Any; + var specificRule = rule.Descriptor.LeftTokenRange.isSpecific() && rule.Descriptor.RightTokenRange.isSpecific(); rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); @@ -67638,27 +68710,14 @@ var ts; (function (formatting) { var Shared; (function (Shared) { - var TokenRangeAccess = (function () { - function TokenRangeAccess(from, to, except) { - this.tokens = []; - for (var token = from; token <= to; token++) { - if (ts.indexOf(except, token) < 0) { - this.tokens.push(token); - } - } - } - TokenRangeAccess.prototype.GetTokens = function () { - return this.tokens; - }; - TokenRangeAccess.prototype.Contains = function (token) { - return this.tokens.indexOf(token) >= 0; - }; - return TokenRangeAccess; - }()); - Shared.TokenRangeAccess = TokenRangeAccess; + var allTokens = []; + for (var token = 0; token <= 142; token++) { + allTokens.push(token); + } var TokenValuesAccess = (function () { - function TokenValuesAccess(tks) { - this.tokens = tks && tks.length ? tks : []; + function TokenValuesAccess(tokens) { + if (tokens === void 0) { tokens = []; } + this.tokens = tokens; } TokenValuesAccess.prototype.GetTokens = function () { return this.tokens; @@ -67666,9 +68725,9 @@ var ts; TokenValuesAccess.prototype.Contains = function (token) { return this.tokens.indexOf(token) >= 0; }; + TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { this.token = token; @@ -67679,18 +68738,14 @@ var ts; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { return tokenValue === this.token; }; + TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { - var result = []; - for (var token = 0; token <= 142; token++) { - result.push(token); - } - return result; + return allTokens; }; TokenAllAccess.prototype.Contains = function () { return true; @@ -67698,51 +68753,80 @@ var ts; TokenAllAccess.prototype.toString = function () { return "[allTokens]"; }; + TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - Shared.TokenAllAccess = TokenAllAccess; - var TokenRange = (function () { - function TokenRange(tokenAccess) { - this.tokenAccess = tokenAccess; + var TokenAllExceptAccess = (function () { + function TokenAllExceptAccess(except) { + this.except = except; } - TokenRange.FromToken = function (token) { - return new TokenRange(new TokenSingleValueAccess(token)); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - TokenRange.FromRange = function (f, to, except) { - if (except === void 0) { except = []; } - return new TokenRange(new TokenRangeAccess(f, to, except)); - }; - TokenRange.AllTokens = function () { - return new TokenRange(new TokenAllAccess()); - }; - TokenRange.prototype.GetTokens = function () { - return this.tokenAccess.GetTokens(); - }; - TokenRange.prototype.Contains = function (token) { - return this.tokenAccess.Contains(token); - }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); - }; - return TokenRange; + TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; + return TokenAllExceptAccess; }()); - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); - TokenRange.Keywords = TokenRange.FromRange(72, 142); - TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([92, 93, 142, 118, 126]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([43, 44, 52, 51]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 71, 19, 21, 17, 99, 94]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([71, 19, 99, 94]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([71, 20, 22, 94]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([71, 19, 99, 94]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([71, 20, 22, 94]); - TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([71, 133, 136, 122, 137, 105, 119]); - Shared.TokenRange = TokenRange; + var TokenRange; + (function (TokenRange) { + function FromToken(token) { + return new TokenSingleValueAccess(token); + } + TokenRange.FromToken = FromToken; + function FromTokens(tokens) { + return new TokenValuesAccess(tokens); + } + TokenRange.FromTokens = FromTokens; + function FromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); + } + TokenRange.FromRange = FromRange; + function AnyExcept(token) { + return new TokenAllExceptAccess(token); + } + TokenRange.AnyExcept = AnyExcept; + TokenRange.Any = new TokenAllAccess(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3])); + TokenRange.Keywords = TokenRange.FromRange(72, 142); + TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ + 92, 93, 142, 118, 126 + ]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ + 43, 44, 52, 51 + ]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ + 8, 71, 19, 21, + 17, 99, 94 + ]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ + 71, 19, 99, 94 + ]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ + 71, 20, 22, 94 + ]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ + 71, 19, 99, 94 + ]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ + 71, 20, 22, 94 + ]); + TokenRange.Comments = TokenRange.FromTokens([2, 3]); + TokenRange.TypeNames = TokenRange.FromTokens([ + 71, 133, 136, 122, + 137, 105, 119 + ]); + })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -67753,6 +68837,8 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); + var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + this.rulesMap = formatting.RulesMap.create(activeRules); } RulesProvider.prototype.getRuleName = function (rule) { return this.globalRules.getRuleName(rule); @@ -67768,121 +68854,9 @@ var ts; }; RulesProvider.prototype.ensureUpToDate = function (options) { if (!this.options || !ts.compareDataObjects(this.options, options)) { - var activeRules = this.createActiveRules(options); - var rulesMap = formatting.RulesMap.create(activeRules); - this.activeRules = activeRules; - this.rulesMap = rulesMap; this.options = ts.clone(options); } }; - RulesProvider.prototype.createActiveRules = function (options) { - var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterConstructor) { - rules.push(this.globalRules.SpaceAfterConstructor); - } - else { - rules.push(this.globalRules.NoSpaceAfterConstructor); - } - if (options.insertSpaceAfterCommaDelimiter) { - rules.push(this.globalRules.SpaceAfterComma); - } - else { - rules.push(this.globalRules.NoSpaceAfterComma); - } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { - rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); - } - else { - rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); - } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { - rules.push(this.globalRules.SpaceAfterKeywordInControl); - } - else { - rules.push(this.globalRules.NoSpaceAfterKeywordInControl); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { - rules.push(this.globalRules.SpaceAfterOpenParen); - rules.push(this.globalRules.SpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenParen); - rules.push(this.globalRules.NoSpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { - rules.push(this.globalRules.SpaceAfterOpenBracket); - rules.push(this.globalRules.SpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBracket); - rules.push(this.globalRules.NoSpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { - rules.push(this.globalRules.SpaceAfterOpenBrace); - rules.push(this.globalRules.SpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBrace); - rules.push(this.globalRules.NoSpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { - rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); - } - else { - rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { - rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); - } - if (options.insertSpaceAfterSemicolonInForStatements) { - rules.push(this.globalRules.SpaceAfterSemicolonInFor); - } - else { - rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); - } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { - rules.push(this.globalRules.SpaceBeforeBinaryOperator); - rules.push(this.globalRules.SpaceAfterBinaryOperator); - } - else { - rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); - rules.push(this.globalRules.NoSpaceAfterBinaryOperator); - } - if (options.insertSpaceBeforeFunctionParenthesis) { - rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl); - } - else { - rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl); - } - if (options.placeOpenBraceOnNewLineForControlBlocks) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); - } - if (options.placeOpenBraceOnNewLineForFunctions) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); - rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); - } - if (options.insertSpaceAfterTypeAssertion) { - rules.push(this.globalRules.SpaceAfterTypeAssertion); - } - else { - rules.push(this.globalRules.NoSpaceAfterTypeAssertion); - } - rules = rules.concat(this.globalRules.LowPriorityCommonRules); - return rules; - }; return RulesProvider; }()); formatting.RulesProvider = RulesProvider; @@ -68067,7 +69041,7 @@ var ts; return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end), options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { - var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRangeHasError; var previousRange; var previousParent; @@ -68150,7 +69124,7 @@ var ts; } case 149: case 146: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -68923,9 +69897,7 @@ var ts; if (node.kind === 20) { return -1; } - if (node.parent && (node.parent.kind === 181 || - node.parent.kind === 182) && - node.parent.expression !== node) { + if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { @@ -69421,7 +70393,7 @@ var ts; }()); textChanges.ChangeTracker = ChangeTracker; function getNonformattedText(node, sourceFile, newLine) { - var options = { newLine: newLine, target: sourceFile.languageVersion }; + var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); printer.writeNode(3, node, sourceFile, writer); @@ -69450,27 +70422,8 @@ var ts; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } - var nullTransformationContext = { - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: function () { return undefined; }, - getCompilerOptions: ts.notImplemented, - getEmitHost: ts.notImplemented, - getEmitResolver: ts.notImplemented, - hoistFunctionDeclaration: ts.noop, - hoistVariableDeclaration: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop - }; function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); var newNode = ts.nodeIsSynthesized(visited) ? visited : (Proxy.prototype = visited, new Proxy()); @@ -69513,6 +70466,16 @@ var ts; setEnd(nodes, _this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; } Writer.prototype.setLastNonTriviaPosition = function (s, force) { if (force || !isTrivia(s)) { @@ -69579,14 +70542,14 @@ var ts; var codefix; (function (codefix) { var codeFixes = []; - function registerCodeFix(action) { - ts.forEach(action.errorCodes, function (error) { + function registerCodeFix(codeFix) { + ts.forEach(codeFix.errorCodes, function (error) { var fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } codefix.registerCodeFix = registerCodeFix; @@ -69609,6 +70572,48 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + var refactors = ts.createMap(); + function registerRefactor(refactor) { + refactors.set(refactor.name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + var results; + var refactorList = []; + refactors.forEach(function (refactor) { + refactorList.push(refactor); + }); + for (var _i = 0, refactorList_1 = refactorList; _i < refactorList_1.length; _i++) { + var refactor_2 = refactorList_1[_i]; + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor_2.isApplicable(context)) { + (results || (results = [])).push({ name: refactor_2.name, description: refactor_2.description }); + } + } + return results; + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getRefactorCodeActions(context, refactorName) { + var result; + var refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + var codeActions = refactor.getCodeActions(context); + if (codeActions) { + ts.addRange((result || (result = [])), codeActions); + } + return result; + } + refactor_1.getRefactorCodeActions = getRefactorCodeActions; + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -69672,7 +70677,8 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { @@ -69750,7 +70756,7 @@ var ts; if (!isStatic) { var stringTypeNode = ts.createKeywordTypeNode(136); var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); - var indexSignature = ts.createIndexSignatureDeclaration(undefined, undefined, [indexingParameter], typeNode); + var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); indexSignatureChangeTracker.insertNodeAfter(sourceFile, openBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ @@ -69764,6 +70770,56 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + function getActionsForCorrectSpelling(context) { + var sourceFile = context.sourceFile; + var node = ts.getTokenAtPosition(sourceFile, context.span.start); + var checker = context.program.getTypeChecker(); + var suggestion; + if (node.kind === 71 && ts.isPropertyAccessExpression(node.parent)) { + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else { + var meaning = ts.getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4) { + flags |= 1920; + } + if (meaning & 2) { + flags |= 793064; + } + if (meaning & 1) { + flags |= 107455; + } + return flags; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -69952,120 +71008,125 @@ var ts; } switch (token.kind) { case 71: - switch (token.parent.kind) { - case 226: - switch (token.parent.parent.parent.kind) { - case 214: - var forStatement = token.parent.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(token.parent); - } - case 216: - var forOfStatement = token.parent.parent.parent; - if (forOfStatement.initializer.kind === 227) { - var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); - } - break; - case 215: - return undefined; - case 260: - var catchClause = token.parent.parent; - var parameter = catchClause.variableDeclaration.getChildren()[0]; - return deleteNode(parameter); - default: - var variableStatement = token.parent.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); - } - else { - return deleteNodeInList(token.parent); - } - } - case 145: - var typeParameters = token.parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); - if (!previousToken || previousToken.kind !== 27) { - return deleteRange(typeParameters); - } - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); - if (!nextToken || nextToken.kind !== 29) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); - } - else { - return deleteNodeInList(token.parent); - } - case 146: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } - case 237: - var importEquals = ts.getAncestor(token, 237); - return deleteNode(importEquals); - case 242: - var namedImports = token.parent.parent; - if (namedImports.elements.length === 1) { - var importSpec = ts.getAncestor(token, 238); - return deleteNode(importSpec); - } - else { - return deleteNodeInList(token.parent); - } - case 239: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238); - return deleteNode(importDecl); - } - else { - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26) { - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); - } - else { - return deleteNode(importClause.name); - } - } - case 240: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { - var importDecl = ts.getAncestor(namespaceImport, 238); - return deleteNode(importDecl); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); - if (previousToken && previousToken.kind === 26) { - var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); - } - return deleteRange(namespaceImport); - } - } - break; + return deleteIdentifier(); case 149: case 240: return deleteNode(token.parent); + default: + return deleteDefault(); } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + function deleteIdentifier() { + switch (token.parent.kind) { + case 226: + return deleteVariableDeclaration(token.parent); + case 145: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); + if (!previousToken || previousToken.kind !== 27) { + return deleteRange(typeParameters); + } + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); + if (!nextToken || nextToken.kind !== 29) { + return deleteRange(typeParameters); + } + return deleteNodeRange(previousToken, nextToken); + } + else { + return deleteNodeInList(token.parent); + } + case 146: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return deleteNode(token.parent); + } + else { + return deleteNodeInList(token.parent); + } + case 237: + var importEquals = ts.getAncestor(token, 237); + return deleteNode(importEquals); + case 242: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + var importSpec = ts.getAncestor(token, 238); + return deleteNode(importSpec); + } + else { + return deleteNodeInList(token.parent); + } + case 239: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = ts.getAncestor(importClause, 238); + return deleteNode(importDecl); + } + else { + var start_4 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 26) { + return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); + } + else { + return deleteNode(importClause.name); + } + } + case 240: + var namespaceImport = token.parent; + if (namespaceImport.name === token && !namespaceImport.parent.name) { + var importDecl = ts.getAncestor(namespaceImport, 238); + return deleteNode(importDecl); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); + if (previousToken && previousToken.kind === 26) { + var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); + return deleteRange({ pos: startPosition, end: namespaceImport.end }); + } + return deleteRange(namespaceImport); + } + default: + return deleteDefault(); + } } - else { - return undefined; + function deleteVariableDeclaration(varDecl) { + switch (varDecl.parent.parent.kind) { + case 214: + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return deleteNode(forInitializer); + } + else { + return deleteNodeInList(varDecl); + } + case 216: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 227); + var forOfInitializer = forOfStatement.initializer; + return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + case 215: + return undefined; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return deleteNode(variableStatement); + } + else { + return deleteNodeInList(varDecl); + } + } } function deleteNode(n) { return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); @@ -70096,6 +71157,15 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ], + getCodeActions: getImportCodeActions + }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; @@ -70178,342 +71248,335 @@ var ts; }; return ImportCodeActionMap; }()); - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); - return getCodeActionForImport(symbol, false, true); + function getImportCodeActions(context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + var cachedImportDeclarations = []; + var lastImportDeclaration; + var currentTokenMeaning = ts.getMeaningFromLocation(token); + if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); + return getCodeActionForImport(symbol, false, true); + } + var candidateModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + candidateModules.push(otherSourceFile.symbol); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); + } + for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { + var moduleSymbol = candidateModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); } } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (cached) { + return cached; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 238) { + return node; } - } - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); - } - } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + if (node.kind === 237) { + return node; } + node = node.parent; } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238) { - return node; + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + if (declaration.kind === 238) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 240) { + namespaceImportDeclaration = declaration; } - if (node.kind === 237) { - return node; + else { + namedImportDeclaration = declaration; } - node = node.parent; + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - return undefined; } - } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); } - return ts.getSymbolId(symbol); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; - } - function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - return getCodeActionsForExistingImport(existingDeclarations); + if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); } else { - return [getCodeActionForNewImport()]; + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; - if (declaration.kind === 238) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240) { - namespaceImportDeclaration = declaration; - } - else { - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248) { + return declaration.moduleReference.expression.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var importList = importClause.namedBindings; + var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); + if (!importList || importList.elements.length === 0) { + var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); + return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 238) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); } else { - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + namespacePrefix = declaration.name.getText(); } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248) { - return declaration.moduleReference.expression.getText(); + namespacePrefix = ts.stripQuotes(namespacePrefix); + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!lastImportDeclaration) { + for (var i = sourceFile.statements.length - 1; i >= 0; i--) { + var statement = sourceFile.statements[i]; + if (statement.kind === 237 || statement.kind === 238) { + lastImportDeclaration = statement; + break; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); - } - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 || statement.kind === 238) { - lastImportDeclaration = statement; - break; - } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var changeTracker = createChangeTracker(); + var importClause = isDefault + ? ts.createImportClause(ts.createIdentifier(name), undefined) + : isNamespaceImport + ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) + : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); + var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + if (!lastImportDeclaration) { + changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); + } + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.fileName; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 265) { + return moduleSymbol.name; } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), undefined) - : isNamespaceImport - ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); - var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265) { - return moduleSymbol.name; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { return undefined; } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); + if (!relativeName) { + return undefined; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - return undefined; - } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { - return undefined; - } - var relativeFileName; - if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { - relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); - } - else { - relativeFileName = getRelativePath(moduleFileName, sourceDirectory); - } - relativeFileName = ts.removeFileExtension(relativeFileName); - if (ts.endsWith(relativeFileName, "/index")) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } - else { - try { - var moduleDirectory = ts.getDirectoryPath(moduleFileName); - var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); - if (packageJsonContent) { - var mainFile = packageJsonContent.main || packageJsonContent.typings; - if (mainFile) { - var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; + } } - catch (e) { } } - return relativeFileName; } + return relativeName; } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); } } return undefined; } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6); + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } } - return fileName; } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; - } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; } } - } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); - } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = getRelativePathIfInDirectory(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } } } - }); + function createChangeTracker() { + return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + } + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; @@ -70628,7 +71691,7 @@ var ts; return undefined; } var declaration = declarations[0]; - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -70677,7 +71740,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -70718,7 +71781,7 @@ var ts; return createStubbedMethod(modifiers, name, optional, undefined, parameters, undefined); } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethodDeclaration(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); + return ts.createMethod(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } codefix.createStubbedMethod = createStubbedMethod; function createStubbedMethodBody() { @@ -70736,8 +71799,173 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor) { + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions: getCodeActions, + isApplicable: isApplicable + }; + refactor.registerRefactor(convertFunctionToES6Class); + function isApplicable(context) { + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + return symbol && symbol.flags & 16 && symbol.members && symbol.members.size > 0; + } + function getCodeActions(context) { + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 | 3))) { + return []; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 228: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 226: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return []; + } + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { + var deleteCallback = deletes_1[_i]; + deleteCallback(); + } + return [{ + description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); + } + else { + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); + } + } + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(115)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + if (!(symbol.flags & 4)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 186: + var functionExpression = assignmentBinaryExpression.right; + return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); + case 187: + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + if (arrowFunctionBody.kind === 207) { + bodyBlock = arrowFunctionBody; + } + else { + var expression = arrowFunctionBody; + bodyBlock = ts.createBlock([ts.createReturn(expression)]); + } + return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); + default: + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + return ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 186) { + return undefined; + } + if (node.name.kind !== 71) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body)); + } + return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); + } + return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + } + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.servicesVersion = "0.5"; + var ruleProvider; function createNode(kind, pos, end, parent) { var node = kind >= 143 ? new NodeObject(kind, pos, end) : kind === 71 ? new IdentifierObject(71, pos, end) : @@ -71116,13 +72344,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_7 !== undefined) { - return result_7; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_8 = getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (declaration.name.kind === 144) { - var expr = declaration.name.expression; + if (name.kind === 144) { + var expr = name.expression; if (expr.kind === 179) { return expr.name.text; } @@ -71465,7 +72694,7 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - var ruleProvider; + ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -71489,9 +72718,6 @@ var ts; return sourceFile; } function getRuleProvider(options) { - if (!ruleProvider) { - ruleProvider = new ts.formatting.RulesProvider(); - } ruleProvider.ensureUpToDate(options); return ruleProvider; } @@ -71718,7 +72944,7 @@ var ts; } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); @@ -71732,7 +72958,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); @@ -71765,11 +72991,11 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); @@ -72017,8 +73243,7 @@ var ts; ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); var preamble = matchArray[1]; var matchPosition = matchArray.index + preamble.length; - var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!ts.isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInComment(sourceFile, matchPosition)) { continue; } var descriptor = undefined; @@ -72066,11 +73291,35 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file, positionOrRange, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken: cancellationToken + }; + } + function getApplicableRefactors(fileName, positionOrRange) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getApplicableRefactors: getApplicableRefactors, + getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -72184,20 +73433,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = ts.getTextOfPropertyName(node.name); if (name && contextualType) { - var result_8 = []; + var result_9 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_8.push(symbol); + result_9.push(symbol); } }); - return result_8; + return result_9; } if (symbol) { - result_8.push(symbol); - return result_8; + result_9.push(symbol); + return result_9; } } return undefined; @@ -72582,6 +73831,9 @@ var ts; CommandNames.GetCodeFixes = "getCodeFixes"; CommandNames.GetCodeFixesFull = "getCodeFixes-full"; CommandNames.GetSupportedCodeFixes = "getSupportedCodeFixes"; + CommandNames.GetApplicableRefactors = "getApplicableRefactors"; + CommandNames.GetRefactorCodeActions = "getRefactorCodeActions"; + CommandNames.GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); function formatMessage(msg, logger, byteLength, newLine) { var verboseLogging = logger.hasLevel(server.LogLevel.verbose); @@ -72915,6 +74167,15 @@ var ts; _a[CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); }, + _a[CommandNames.GetApplicableRefactors] = function (request) { + return _this.requiredResponse(_this.getApplicableRefactors(request.arguments)); + }, + _a[CommandNames.GetRefactorCodeActions] = function (request) { + return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, true)); + }, + _a[CommandNames.GetRefactorCodeActionsFull] = function (request) { + return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, false)); + }, _a)); this.host = opts.host; this.cancellationToken = opts.cancellationToken; @@ -72945,7 +74206,8 @@ var ts; throttleWaitMilliseconds: throttleWaitMilliseconds, eventHandler: this.eventHandler, globalPlugins: opts.globalPlugins, - pluginProbeLocations: opts.pluginProbeLocations + pluginProbeLocations: opts.pluginProbeLocations, + allowLocalPluginLoads: opts.allowLocalPluginLoads }; this.projectService = new server.ProjectService(settings); this.gcTimer = new server.GcTimer(this.host, 7000, this.logger); @@ -73881,6 +75143,47 @@ var ts; Session.prototype.getSupportedCodeFixes = function () { return ts.getSupportedCodeFixes(); }; + Session.prototype.isLocation = function (locationOrSpan) { + return locationOrSpan.line !== undefined; + }; + Session.prototype.extractPositionAndRange = function (args, scriptInfo) { + var position = undefined; + var textRange; + if (this.isLocation(args)) { + position = getPosition(args); + } + else { + var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition; + textRange = { pos: startPosition, end: endPosition }; + } + return { position: position, textRange: textRange }; + function getPosition(loc) { + return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); + } + }; + Session.prototype.getApplicableRefactors = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; + return project.getLanguageService().getApplicableRefactors(file, position || textRange); + }; + Session.prototype.getRefactorCodeActions = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; + var result = project.getLanguageService().getRefactorCodeActions(file, this.projectService.getFormatCodeOptions(), position || textRange, args.refactorName); + if (simplifiedResult) { + return { + actions: result.map(function (action) { return _this.mapCodeAction(action, scriptInfo); }) + }; + } + else { + return { + actions: result + }; + } + }; Session.prototype.getCodeFixes = function (args, simplifiedResult) { var _this = this; if (args.errorCodes.length === 0) { @@ -73888,8 +75191,7 @@ var ts; } var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var startPosition = getStartPosition(); - var endPosition = getEndPosition(); + var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; var formatOptions = this.projectService.getFormatCodeOptions(file); var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, formatOptions); if (!codeActions) { @@ -73901,12 +75203,24 @@ var ts; else { return codeActions; } - function getStartPosition() { - return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + }; + Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { + var startPosition = undefined, endPosition = undefined; + if (args.startPosition !== undefined) { + startPosition = args.startPosition; } - function getEndPosition() { - return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + else { + startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + args.startPosition = startPosition; } + if (args.endPosition !== undefined) { + endPosition = args.endPosition; + } + else { + endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + args.endPosition = endPosition; + } + return { startPosition: startPosition, endPosition: endPosition }; }; Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { var _this = this; @@ -76213,7 +77527,7 @@ var ts; var oldProgram = this.program; this.program = this.languageService.getProgram(); var hasChanges = false; - if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { + if (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2))) { hasChanges = true; if (oldProgram) { for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { @@ -76470,6 +77784,11 @@ var ts; return; } var searchPaths = [ts.combinePaths(host.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"); + searchPaths.unshift(local); + } if (options.plugins) { for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { var pluginConfigEntry = _a[_i]; @@ -76854,6 +78173,7 @@ var ts; this.eventHandler = opts.eventHandler; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; + this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.directoryWatchers = new DirectoryWatchers(this); @@ -78429,6 +79749,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations @@ -78591,3 +79914,5 @@ var TypeScript; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); var toolsVersion = "2.4"; + +//# sourceMappingURL=tsserverlibrary.js.map diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 2f11d458e20..5853aafb946 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -359,9 +359,10 @@ declare namespace ts { SyntaxList = 294, NotEmittedStatement = 295, PartiallyEmittedExpression = 296, - MergeDeclarationMarker = 297, - EndOfDeclarationMarker = 298, - Count = 299, + CommaListExpression = 297, + MergeDeclarationMarker = 298, + EndOfDeclarationMarker = 299, + Count = 300, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -474,6 +475,10 @@ declare namespace ts { type ModifiersArray = NodeArray; interface Identifier extends PrimaryExpression { kind: SyntaxKind.Identifier; + /** + * Text of identifier (with escapes converted to characters). + * If the identifier begins with two underscores, this will begin with three. + */ text: string; originalKeywordKind?: SyntaxKind; isInJSDocNamespace?: boolean; @@ -491,9 +496,11 @@ declare namespace ts { type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { name?: DeclarationName; } - interface DeclarationStatement extends Declaration, Statement { + interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { @@ -504,7 +511,7 @@ declare namespace ts { kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } - interface TypeParameterDeclaration extends Declaration { + interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -512,7 +519,7 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends Declaration { + interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -525,7 +532,7 @@ declare namespace ts { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; - interface VariableDeclaration extends Declaration { + interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; @@ -537,7 +544,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends Declaration { + interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -546,7 +553,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface BindingElement extends Declaration { + interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; @@ -568,7 +575,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface ObjectLiteralElement extends Declaration { + interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -590,7 +597,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends Declaration { + interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -598,7 +605,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface PropertyLikeDeclaration extends Declaration { + interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } interface ObjectBindingPattern extends Node { @@ -950,7 +957,7 @@ declare namespace ts { } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - interface PropertyAccessExpression extends MemberExpression, Declaration { + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1016,7 +1023,7 @@ declare namespace ts { } interface MetaProperty extends PrimaryExpression { kind: SyntaxKind.MetaProperty; - keywordToken: SyntaxKind; + keywordToken: SyntaxKind.NewKeyword; name: Identifier; } interface JsxElement extends PrimaryExpression { @@ -1076,6 +1083,13 @@ declare namespace ts { interface NotEmittedStatement extends Statement { kind: SyntaxKind.NotEmittedStatement; } + /** + * A list of comma-seperated expressions. This node is only created by transformations. + */ + interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; + elements: NodeArray; + } interface EmptyStatement extends Statement { kind: SyntaxKind.EmptyStatement; } @@ -1197,7 +1211,7 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - interface ClassLikeDeclaration extends Declaration { + interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1210,11 +1224,11 @@ declare namespace ts { interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { kind: SyntaxKind.ClassExpression; } - interface ClassElement extends Declaration { + interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - interface TypeElement extends Declaration { + interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1238,7 +1252,7 @@ declare namespace ts { typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends Declaration { + interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; @@ -1297,13 +1311,13 @@ declare namespace ts { moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; - interface ImportClause extends Declaration { + interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } - interface NamespaceImport extends Declaration { + interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1330,13 +1344,13 @@ declare namespace ts { elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; - interface ImportSpecifier extends Declaration { + interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; name: Identifier; } - interface ExportSpecifier extends Declaration { + interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; @@ -1467,7 +1481,7 @@ declare namespace ts { kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } - interface JSDocTypedefTag extends JSDocTag, Declaration { + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -1706,11 +1720,11 @@ declare namespace ts { /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; + getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; - getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; @@ -1720,38 +1734,48 @@ declare namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + getContextualType(node: Expression): Type | undefined; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type; + getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; + getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; + getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; } enum NodeBuilderFlags { None = 0, - allowThisInObjectLiteral = 1, - allowQualifedNameInPlaceOfIdentifier = 2, - allowTypeParameterInQualifiedName = 4, - allowAnonymousIdentifier = 8, - allowEmptyUnionOrIntersection = 16, - allowEmptyTuple = 32, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + AllowThisInObjectLiteral = 1024, + AllowQualifedNameInPlaceOfIdentifier = 2048, + AllowAnonymousIdentifier = 8192, + AllowEmptyUnionOrIntersection = 16384, + AllowEmptyTuple = 32768, + IgnoreErrors = 60416, + InObjectTypeLiteral = 1048576, + InTypeAlias = 8388608, } interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1912,18 +1936,18 @@ declare namespace ts { Index = 262144, IndexedAccess = 524288, NonPrimitive = 16777216, - Literal = 480, + Literal = 224, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, StringLike = 262178, - NumberLike = 340, + NumberLike = 84, BooleanLike = 136, EnumLike = 272, UnionOrIntersection = 196608, StructuredType = 229376, StructuredOrTypeVariable = 1032192, TypeVariable = 540672, - Narrowable = 17810431, + Narrowable = 17810175, NotUnionOrUnit = 16810497, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; @@ -1935,15 +1959,17 @@ declare namespace ts { aliasTypeArguments?: Type[]; } interface LiteralType extends Type { - text: string; + value: string | number; freshType?: LiteralType; regularType?: LiteralType; } - interface EnumType extends Type { - memberTypes: EnumLiteralType[]; + interface StringLiteralType extends LiteralType { + value: string; } - interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; + interface NumberLiteralType extends LiteralType { + value: number; + } + interface EnumType extends Type { } enum ObjectFlags { Class = 1, @@ -1988,7 +2014,7 @@ declare namespace ts { */ interface TypeReference extends ObjectType { target: GenericType; - typeArguments: Type[]; + typeArguments?: Type[]; } interface GenericType extends InterfaceType, TypeReference { } @@ -2024,7 +2050,7 @@ declare namespace ts { } interface Signature { declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; + typeParameters?: TypeParameter[]; parameters: Symbol[]; } enum IndexKind { @@ -2059,9 +2085,9 @@ declare namespace ts { next?: DiagnosticMessageChain; } interface Diagnostic { - file: SourceFile; - start: number; - length: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; messageText: string | DiagnosticMessageChain; category: DiagnosticCategory; code: number; @@ -2329,6 +2355,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, + NoAsciiEscaping = 16777216, } interface EmitHelper { readonly name: string; @@ -2611,14 +2638,14 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; /** Optionally, get the shebang */ - function getShebang(text: string): string; + function getShebang(text: string): string | undefined; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; @@ -2709,6 +2736,7 @@ declare namespace ts { function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; + function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; /** Create a unique temporary variable for use in a loop. */ @@ -2727,58 +2755,19 @@ declare namespace ts { function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; - function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): SignatureDeclaration; - function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; - function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; - function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; - function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; - function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; - function createThisTypeNode(): ThisTypeNode; - function createLiteralTypeNode(literal: Expression): LiteralTypeNode; - function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; - function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; - function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; - function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; - function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; - function createTypeQueryNode(exprName: EntityName): TypeQueryNode; - function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; - function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; - function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray): UnionOrIntersectionTypeNode; - function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; - function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; - function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; - function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; - function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; - function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; - function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; - function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; - function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; function createDecorator(expression: Expression): Decorator; function updateDecorator(node: Decorator, expression: Expression): Decorator; + function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; - function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function createConstructor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; @@ -2786,6 +2775,45 @@ declare namespace ts { function updateGetAccessor(node: GetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; function createSetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; function updateSetAccessor(node: SetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; + function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; + function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; + function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; + function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; + function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; + function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; + function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; + function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; + function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; + function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; + function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; + function createTypeQueryNode(exprName: EntityName): TypeQueryNode; + function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; + function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; + function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; + function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; + function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; + function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; + function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; + function createUnionTypeNode(types: TypeNode[]): UnionTypeNode; + function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; + function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode; + function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionTypeNode | IntersectionTypeNode; + function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; + function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; + function createThisTypeNode(): ThisTypeNode; + function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; + function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function createLiteralTypeNode(literal: Expression): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; function createObjectBindingPattern(elements: BindingElement[]): ObjectBindingPattern; function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern; function createArrayBindingPattern(elements: ArrayBindingElement[]): ArrayBindingPattern; @@ -2827,7 +2855,7 @@ declare namespace ts { function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; - function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression; + function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; @@ -2847,16 +2875,15 @@ declare namespace ts { function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; function createNonNullExpression(expression: Expression): NonNullExpression; function updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression; + function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function createSemicolonClassElement(): SemicolonClassElement; function createBlock(statements: Statement[], multiLine?: boolean): Block; function updateBlock(node: Block, statements: Statement[]): Block; function createVariableStatement(modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList | VariableDeclaration[]): VariableStatement; function updateVariableStatement(node: VariableStatement, modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList): VariableStatement; - function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; - function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; - function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; - function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; function createEmptyStatement(): EmptyStatement; function createStatement(expression: Expression): ExpressionStatement; function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; @@ -2888,10 +2915,19 @@ declare namespace ts { function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement; function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function createDebuggerStatement(): DebuggerStatement; + function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; + function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; + function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function createClassDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; + function createInterfaceDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; function createEnumDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, members: EnumMember[]): EnumDeclaration; function updateEnumDeclaration(node: EnumDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, members: EnumMember[]): EnumDeclaration; function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; @@ -2900,6 +2936,8 @@ declare namespace ts { function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock; function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock; function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; + function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function createImportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; @@ -2930,20 +2968,20 @@ declare namespace ts { function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; - function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; - function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; - function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; - function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCaseClause(expression: Expression, statements: Statement[]): CaseClause; function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]): CaseClause; function createDefaultClause(statements: Statement[]): DefaultClause; function updateDefaultClause(node: DefaultClause, statements: Statement[]): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause; function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause; function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; @@ -2976,6 +3014,8 @@ declare namespace ts { */ function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createCommaList(elements: Expression[]): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: Expression[]): CommaListExpression; function createBundle(sourceFiles: SourceFile[]): Bundle; function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; function createComma(left: Expression, right: Expression): Expression; @@ -3040,11 +3080,11 @@ declare namespace ts { /** * Gets the constant value to emit for an expression. */ - function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; /** * Sets the constant value to emit for an expression. */ - function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression; + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression; /** * Adds an EmitHelper to a node. */ @@ -3069,17 +3109,13 @@ declare namespace ts { } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; - function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; function isExternalModule(file: SourceFile): boolean; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - /** Array that is only intended to be pushed to, never read. */ - interface Push { - push(value: T): void; - } function moduleHasNonRelativeName(moduleName: string): boolean; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; @@ -3218,6 +3254,7 @@ declare namespace ts { getNewLine(): string; } function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } @@ -3246,9 +3283,10 @@ declare namespace ts { * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine; - function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -3422,6 +3460,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; + getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -3492,6 +3532,10 @@ declare namespace ts { /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; } + interface ApplicableRefactorInfo { + name: string; + description: string; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -4006,6 +4050,7 @@ declare namespace ts { reportDiagnostics?: boolean; moduleName?: string; renamedDependencies?: MapLike; + transformers?: CustomTransformers; } interface TranspileOutput { outputText: string; diff --git a/lib/typescript.js b/lib/typescript.js index 4fe0eb9bf25..9f28644b4e5 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -365,10 +365,11 @@ var ts; // Transformation nodes SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -512,6 +513,13 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + /* @internal */ + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); /** Return code used by getEmitOutput function to indicate status of the function */ var ExitStatus; (function (ExitStatus) { @@ -527,12 +535,23 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + // Options + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + // Error handling + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + // State + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { @@ -677,6 +696,12 @@ var ts; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); /* @internal */ + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type) + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + /* @internal */ var CheckFlags; (function (CheckFlags) { CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; @@ -751,7 +776,7 @@ var ts; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; @@ -761,7 +786,7 @@ var ts; /* @internal */ TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; @@ -770,7 +795,7 @@ var ts; TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 17810431] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; @@ -1119,6 +1144,7 @@ var ts; EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1138,17 +1164,22 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; // Helpers included by ES2017 for..await..of - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; // Helpers included by ES2015 spread ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1450,12 +1481,6 @@ var ts; return undefined; } ts.forEach = forEach; - /** - * Iterates through the parent chain of a node and performs the callback on each parent until the callback - * returns a truthy value, then returns that value. - * If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit" - * At that point findAncestor returns undefined. - */ function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1477,6 +1502,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; /** * Iterates through `array` by index and performs the callback on each element of array until the callback * returns a falsey value, then returns false. @@ -1704,6 +1738,35 @@ var ts; return result; } ts.flatMap = flatMap; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * Avoids allocation if all elements map to themselves. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -2881,6 +2944,11 @@ var ts; } ts.startsWith = startsWith; /* @internal */ + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + /* @internal */ function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -4058,6 +4126,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -4165,7 +4234,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -4360,6 +4429,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4655,6 +4732,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -4700,6 +4778,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4781,6 +4861,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -5443,9 +5526,10 @@ var ts; ts.getTrailingCommentRanges = getTrailingCommentRanges; /** Optionally, get the shebang */ function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -6654,9 +6738,7 @@ var ts; ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; /* @internal */ function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -6849,28 +6931,30 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, - // or an escaped quoted form of the original text if it's string-like. + // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { case 9 /* StringLiteral */: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13 /* NoSubstitutionTemplateLiteral */: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14 /* TemplateHead */: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15 /* TemplateMiddle */: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16 /* TemplateTail */: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8 /* NumericLiteral */: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier; @@ -7099,10 +7183,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 /* EnumDeclaration */ && isConst(node); } @@ -7382,6 +7462,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151 /* MethodDeclaration */: @@ -7638,6 +7727,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 /* CallExpression */ || node.kind === 182 /* NewExpression */; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183 /* TaggedTemplateExpression */) { return node.tag; @@ -8230,21 +8323,46 @@ var ts; ts.isInAmbientContext = isInAmbientContext; // True if the given identifier, string literal, or number literal is the name of a declaration node function isDeclarationName(name) { - if (name.kind !== 71 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) { - return false; + switch (name.kind) { + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 /* ImportSpecifier */ || parent.kind === 246 /* ExportSpecifier */) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194 /* BinaryExpression */) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0 /* None */: + case 2 /* ModuleExports */: + return undefined; + case 1 /* ExportsProperty */: + if (lhs.kind === 71 /* Identifier */) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4 /* ThisProperty */: + case 5 /* Property */: + return lhs.name; + case 3 /* PrototypeProperty */: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 144 /* ComputedPropertyName */ && @@ -8357,21 +8475,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -8399,12 +8515,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } var flags = 0 /* Normal */; switch (node.kind) { case 228 /* FunctionDeclaration */: @@ -8457,7 +8574,8 @@ var ts; * Symbol. */ function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -8740,6 +8858,8 @@ var ts; return 2; case 198 /* SpreadElement */: return 1; + case 297 /* CommaListExpression */: + return 0; default: return -1; } @@ -8853,14 +8973,15 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); // Replace non-ASCII characters with '\uNNNN' escapes if any exist. // Otherwise just return the original string. return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -8949,7 +9070,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -9015,7 +9136,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; /** @@ -9579,13 +9700,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0 /* CarriageReturnLineFeed */) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0 /* CarriageReturnLineFeed */: + return carriageReturnLineFeed; + case 1 /* LineFeed */: + return lineFeed; } - else if (options.newLine === 1 /* LineFeed */) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -9913,10 +10034,6 @@ var ts; return node.kind === 71 /* Identifier */; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190 /* VoidExpression */; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return isIdentifier(node) && node.autoGenerateKind > 0 /* None */; @@ -9989,9 +10106,20 @@ var ts; || kind === 153 /* GetAccessor */ || kind === 154 /* SetAccessor */ || kind === 157 /* IndexSignature */ - || kind === 206 /* SemicolonClassElement */; + || kind === 206 /* SemicolonClassElement */ + || kind === 247 /* MissingDeclaration */; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 /* ConstructSignature */ + || kind === 155 /* CallSignature */ + || kind === 148 /* PropertySignature */ + || kind === 150 /* MethodSignature */ + || kind === 157 /* IndexSignature */ + || kind === 247 /* MissingDeclaration */; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 /* PropertyAssignment */ @@ -10209,6 +10337,7 @@ var ts; || kind === 198 /* SpreadElement */ || kind === 202 /* AsExpression */ || kind === 200 /* OmittedExpression */ + || kind === 297 /* CommaListExpression */ || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -10297,6 +10426,10 @@ var ts; return node.kind === 237 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238 /* ImportDeclaration */; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239 /* ImportClause */; } @@ -10319,6 +10452,10 @@ var ts; return node.kind === 246 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243 /* ExportAssignment */; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 /* ModuleDeclaration */ || node.kind === 232 /* EnumDeclaration */; } @@ -10390,8 +10527,8 @@ var ts; || kind === 213 /* WhileStatement */ || kind === 220 /* WithStatement */ || kind === 295 /* NotEmittedStatement */ - || kind === 298 /* EndOfDeclarationMarker */ - || kind === 297 /* MergeDeclarationMarker */; + || kind === 299 /* EndOfDeclarationMarker */ + || kind === 298 /* MergeDeclarationMarker */; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -10517,6 +10654,49 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 6 /* Synthetic */) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + // shift current back to previous, and then reuse previous' array + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -10983,16 +11163,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - // Identifiers - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71 /* Identifier */); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; node.autoGenerateKind = 0 /* None */; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable) { @@ -11087,240 +11275,13 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - // Type Elements - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - // Types - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169 /* ThisType */); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173 /* LiteralType */); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159 /* TypeReference */); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158 /* TypePredicate */); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162 /* TypeQuery */); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164 /* ArrayType */); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168 /* ParenthesizedType */); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163 /* TypeLiteral */); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165 /* TupleType */); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172 /* MappedType */); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170 /* TypeOperator */); - typeOperatorNode.operator = 127 /* KeyOfKeyword */; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171 /* IndexedAccessType */); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; - // Type Declarations + // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145 /* TypeParameter */); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145 /* TypeParameter */); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -11331,44 +11292,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - // Signature elements - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148 /* PropertySignature */); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157 /* IndexSignature */); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; - // Signature elements function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146 /* Parameter */); node.decorators = asNodeArray(decorators); @@ -11405,7 +11328,27 @@ var ts; : node; } ts.updateDecorator = updateDecorator; - // Type members + // Type Elements + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148 /* PropertySignature */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); @@ -11427,7 +11370,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -11440,7 +11400,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -11450,7 +11410,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -11518,6 +11478,251 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157 /* IndexSignature */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + /* @internal */ + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + // Types + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158 /* TypePredicate */); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159 /* TypeReference */); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162 /* TypeQuery */); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163 /* TypeLiteral */); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164 /* ArrayType */); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165 /* TupleType */); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166 /* UnionType */, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167 /* IntersectionType */, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168 /* ParenthesizedType */); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169 /* ThisType */); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170 /* TypeOperator */); + node.operator = 127 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171 /* IndexedAccessType */); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172 /* MappedType */); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173 /* LiteralType */); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174 /* ObjectBindingPattern */); @@ -11565,9 +11770,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -11580,9 +11784,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -11632,9 +11835,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -11824,10 +12027,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -11954,6 +12157,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204 /* MetaProperty */); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205 /* TemplateSpan */); @@ -11969,6 +12185,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206 /* SemicolonClassElement */); + } + ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { var block = createSynthesizedNode(207 /* Block */); @@ -11979,7 +12199,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -11999,35 +12219,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227 /* VariableDeclarationList */); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226 /* VariableDeclaration */); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209 /* EmptyStatement */); } @@ -12246,6 +12437,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225 /* DebuggerStatement */); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226 /* VariableDeclaration */); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227 /* VariableDeclarationList */); + node.flags |= flags & 3 /* BlockScoped */; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); @@ -12294,6 +12518,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230 /* InterfaceDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231 /* TypeAliasDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); @@ -12314,7 +12580,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233 /* ModuleDeclaration */); - node.flags |= flags; + node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -12355,6 +12621,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236 /* NamespaceExportDeclaration */); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); @@ -12385,7 +12663,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -12573,19 +12852,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254 /* JsxAttributes */); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253 /* JsxAttribute */); node.name = name; @@ -12600,6 +12866,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254 /* JsxAttributes */); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255 /* JsxSpreadAttribute */); node.expression = expression; @@ -12626,20 +12904,6 @@ var ts; } ts.updateJsxExpression = updateJsxExpression; // Clauses - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259 /* HeritageClause */); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); @@ -12648,10 +12912,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -12661,12 +12925,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259 /* HeritageClause */); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260 /* CatchClause */); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -12675,10 +12951,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; // Property assignments @@ -12691,10 +12967,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -12705,10 +12981,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -12718,10 +12994,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; // Enum @@ -12833,7 +13108,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -12845,7 +13120,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(298 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -12874,6 +13149,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297 /* CommaListExpression */) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297 /* CommaListExpression */); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266 /* Bundle */); node.sourceFiles = sourceFiles; @@ -13250,7 +13548,25 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - // Compound nodes + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -13512,7 +13828,11 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -13686,9 +14006,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) @@ -13846,16 +14167,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195 /* ConditionalExpression */, 55 /* QuestionToken */); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -14131,6 +14442,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166 /* UnionType */: + case 167 /* IntersectionType */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; /** * Clones a series of not-emitted expressions with a new inner expression. * @@ -14311,7 +14650,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -15079,6 +15418,8 @@ var ts; return visitNode(cbNode, node.expression); case 247 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); + case 297 /* CommaListExpression */: + return visitNodes(cbNodes, node.elements); case 249 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -20465,6 +20806,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -21452,7 +21795,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -21480,7 +21823,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { // bind in strict mode source files with alwaysStrict option return true; } @@ -21517,12 +21860,13 @@ 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.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; @@ -21530,7 +21874,7 @@ var ts; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152 /* Constructor */: @@ -21674,9 +22018,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } @@ -23592,7 +23936,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) checkStrictModeEvalOrArguments(node, node.name); @@ -23611,7 +23955,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -23626,7 +23970,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -23639,7 +23983,7 @@ var ts; return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -24526,13 +24870,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - /** Adds `isExernalLibraryImport` to a Resolved to get a ResolvedModule. */ - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -24860,6 +25202,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -25062,13 +25406,24 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, /*jsOnly*/ false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ /* @internal */ - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -25099,7 +25454,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -25462,6 +25816,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -25613,13 +25968,16 @@ var ts; // since we are only interested in declarations of the module itself return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -25702,11 +26060,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32 /* StringLiteral */, ""); - var zeroType = getLiteralTypeForText(64 /* NumberLiteral */, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -25972,16 +26332,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -26063,9 +26423,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 /* Object */ ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } @@ -26073,7 +26430,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -26109,7 +26466,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { // nodes are in different files and order cannot be determined return true; } @@ -26205,7 +26563,11 @@ var ts; // Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and // the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with // the given name can be found. - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; var propertyWithInvalidInitializer; @@ -26215,7 +26577,7 @@ var ts; loop: while (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { // symbol lookup restrictions for function-like declarations @@ -26286,12 +26648,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { + if (result = lookup(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { break loop; } break; case 232 /* EnumDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; @@ -26306,7 +26668,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 107455 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -26316,7 +26678,7 @@ var ts; case 229 /* ClassDeclaration */: case 199 /* ClassExpression */: case 230 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -26351,7 +26713,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -26412,7 +26774,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -26422,7 +26784,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -26541,6 +26913,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -26573,13 +26949,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2 /* BlockScopedVariable */) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32 /* Class */) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384 /* Enum */) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256 /* RegularEnum */) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -26595,7 +26971,7 @@ var ts; if (node.kind === 237 /* ImportEqualsDeclaration */) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238 /* ImportDeclaration */; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -26719,10 +27095,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); @@ -26738,7 +27114,7 @@ var ts; case 242 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 243 /* ExportAssignment */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236 /* NamespaceExportDeclaration */: @@ -26887,7 +27263,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -26909,6 +27285,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, /*withAugmentations*/ true); if (ambientModule) { return ambientModule; @@ -26978,7 +27359,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -27128,7 +27508,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32 /* StringLiteral */, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } // A reserved member name starts with two underscores, but the third character cannot be an underscore // or the @ symbol. A third underscore indicates an escaped form of an identifer that started @@ -27458,34 +27838,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 /* NoTruncation */ ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4 /* NoTruncation */) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128 /* UseFullyQualifiedType */) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048 /* SuppressAnyReturnType */) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1 /* WriteArrayAsGenericType */) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32 /* WriteTypeArgumentsOfSignature */) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -27495,15 +27900,14 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; - // TODO(aozgaa): should we return implict any (undefined) or explicit any (keywordtypenode)? return undefined; } if (type.flags & 1 /* Any */) { @@ -27518,23 +27922,25 @@ var ts; if (type.flags & 8 /* Boolean */) { return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } - if (type.flags & 16 /* Enum */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + } + if (type.flags & 272 /* EnumLike */) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (32 /* StringLiteral */)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } if (type.flags & (64 /* NumberLiteral */)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128 /* BooleanLiteral */) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256 /* EnumLiteral */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); - } if (type.flags & 1024 /* Void */) { return ts.createKeywordTypeNode(105 /* VoidKeyword */); } @@ -27554,8 +27960,8 @@ var ts; return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -27566,39 +27972,31 @@ var ts; ts.Debug.assert(!!(type.flags & 32768 /* Object */)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3 /* ClassOrInterface */) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - // TODO(aozgaa): handle type arguments. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); - } - if (type.flags & 16384 /* TypeParameter */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & 16384 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536 /* Union */) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166 /* UnionType */, unionTypeNodes); + if (type.flags & (65536 /* Union */ | 131072 /* Intersection */)) { + var types = type.flags & 65536 /* Union */ ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 /* Union */ ? 166 /* UnionType */ : 167 /* IntersectionType */, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072 /* Intersection */) { - return ts.createUnionOrIntersectionTypeNode(167 /* IntersectionType */, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { ts.Debug.assert(!!(type.flags & 32768 /* Object */)); // The type is an object literal type. @@ -27606,35 +28004,23 @@ var ts; } if (type.flags & 262144 /* Index */) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288 /* IndexedAccess */) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -27643,14 +28029,14 @@ var ts; if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); } else if (ts.contains(context.symbolStack, symbol)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - var entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false); + var entityName = symbolToName(typeAlias, context, 793064 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -27696,41 +28082,53 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(/*members*/ undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, /*expectsIdentifier*/ false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + // Unnamed function expressions and arrow functions have reserved names that we don't want to display + var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8 /* Tuple */) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -27738,7 +28136,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -27751,48 +28149,72 @@ var ts; // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - var qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, /*right*/ undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); + qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71 /* Identifier */) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71 /* Identifier */) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); } var properties = resolvedType.properties; if (!properties) { @@ -27801,86 +28223,131 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - // TODO(aozgaa): should we create a node with explicit or implict any? - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119 /* AnyKeyword */); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 136 /* StringKeyword */ : 133 /* NumberKeyword */); - var name = ts.getNameFromIndexInfo(indexInfo); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration( + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 /* Identifier */ ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 /* AnyKeyword */ ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, /*expectsIdentifier*/ true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146 /* Parameter */); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration.name.kind === 71 /* Identifier */ ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - // TODO(aozgaa): In the future, check initializer accessibility. - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24 /* DotDotDotToken */), - // Clone name to remove trivia. - ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55 /* QuestionToken */), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048 /* Undefined */); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter( + /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + /*initializer*/ undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176 /* BindingElement */) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0 /* None */, /*endOfChain*/ true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -27888,19 +28355,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); - // const parentIndex = index - 1; var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -27909,20 +28375,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ @@ -27954,28 +28410,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199 /* ClassExpression */: - return "(Anonymous class)"; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199 /* ClassExpression */: + return "(Anonymous class)"; + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -27993,12 +28450,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144 /* Nullable */)) { if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { - var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536 /* Union */) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -28034,13 +28493,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -28097,7 +28557,7 @@ var ts; if (parentSymbol) { // Write type arguments of instantiated class/interface here if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -28180,12 +28640,17 @@ var ts; else if (getObjectFlags(type) & 4 /* Reference */) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256 /* EnumLiteral */) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - writePunctuation(writer, 23 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); + // In a literal enum type with a single member E { A }, E and E.A denote the + // same type. We always display this type simply as E. + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23 /* DotToken */); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (16 /* Enum */ | 16384 /* TypeParameter */)) { + else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 16384 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } @@ -28541,7 +29006,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048 /* Undefined */); + type = getNullableType(type, 2048 /* Undefined */); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -28808,10 +29273,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246 /* ExportSpecifier */) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } var result = []; if (exportSymbol) { @@ -28954,7 +29416,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -29070,7 +29532,7 @@ var ts; return expr.kind === 177 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + return strictNullChecks && optional ? getNullableType(type, 2048 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { @@ -29173,6 +29635,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 /* BinaryExpression */ ? declaration : @@ -29189,17 +29652,25 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536 /* JavaScriptFile */) { - // If there is a JSDoc type, use it - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + // If there is a JSDoc type, use it + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + // If we don't have an explicit JSDoc type, get the type from the expression. + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, /*subtypeReduction*/ true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, /*subtypeReduction*/ true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding @@ -29449,7 +29920,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? getNullableType(type, 2048 /* Undefined */) : type; } } } @@ -29512,7 +29983,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -29711,6 +30182,7 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && @@ -29718,7 +30190,7 @@ var ts; // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the // class and all return the instance type of the class. There is no need for further checks and we can apply the // type arguments in the same manner as a type reference to get the same error reporting experience. - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; @@ -29902,77 +30374,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 /* NumericLiteral */ || + return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || expr.kind === 192 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */ || - expr.kind === 71 /* Identifier */ && !!symbol.exports.get(expr.text); + expr.kind === 71 /* Identifier */ && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256 /* EnumLiteral */); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16 /* Enum */); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232 /* EnumDeclaration */) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1 /* Literal */) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536 /* Union */; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); + if (enumType_1.flags & 65536 /* Union */) { + enumType_1.flags |= 256 /* EnumLiteral */; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16 /* Enum */); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 /* Union */ ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -30219,7 +30694,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -30306,8 +30781,8 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type = types_2[_i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -30481,7 +30956,7 @@ var ts; // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (t.flags & 32 /* StringLiteral */) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864 /* Optional */); var prop = createSymbol(4 /* Property */ | (isOptional ? 67108864 /* Optional */ : 0), propName); @@ -30613,6 +31088,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536 /* Union */) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190 /* Primitive */) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : type.flags & 524288 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : @@ -30674,8 +31170,8 @@ var ts; if (t.flags & 196608 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -30731,7 +31227,7 @@ var ts; var t = type.flags & 540672 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 /* StringLike */ ? globalStringType : - t.flags & 340 /* NumberLike */ ? globalNumberType : + t.flags & 84 /* NumberLike */ ? globalNumberType : t.flags & 136 /* BooleanLike */ ? globalBooleanType : t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : @@ -30746,12 +31242,12 @@ var ts; var commonFlags = isUnion ? 0 /* None */ : 67108864 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -30823,7 +31319,7 @@ var ts; function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); // We need to filter out partial properties in union types - return property && !(getCheckFlags(property) & 16 /* Partial */) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined; } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when @@ -31231,8 +31727,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -31367,8 +31864,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -31399,7 +31896,7 @@ var ts; return ts.length(type.target.typeParameters); } // Get type from reference to class or interface - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -31414,7 +31911,7 @@ var ts; // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -31437,7 +31934,7 @@ var ts; // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the // declared type. Instantiations are cached using the type identities of the type arguments as the key. - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -31449,7 +31946,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -31489,14 +31985,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064 /* Type */) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288 /* TypeAlias */) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 /* Value */ && node.kind === 277 /* JSDocTypeReference */) { // A JSDocTypeReference may have resolved to a value (as opposed to a type). In @@ -31559,10 +32056,7 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064 /* Type */) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the // type reference in checkTypeReferenceOrExpressionWithTypeArguments. @@ -31571,6 +32065,9 @@ var ts; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -31812,14 +32309,14 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -31827,8 +32324,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -31959,8 +32456,8 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -32024,9 +32521,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32 /* StringLiteral */, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -32056,12 +32553,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */ | 256 /* EnumLiteral */) ? - indexType.text : + var propName = indexType.flags & 96 /* StringOrNumberLiteral */ ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -32076,11 +32573,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { @@ -32105,7 +32602,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 /* String */ | 4 /* Number */)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -32258,7 +32755,7 @@ var ts; var rightProp = _a[_i]; // we approximate own properties as non-methods plus methods that are inside the object literal var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -32275,11 +32772,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 67108864 /* Optional */) { + if (rightProp.flags & 67108864 /* Optional */) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 67108864 /* Optional */); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -32306,15 +32803,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 1048576 /* FreshLiteral */)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.text); + var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -32325,11 +32823,17 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 /* StringLiteral */ ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 /* NumberLiteral */ : 32 /* StringLiteral */) | (enumId ? 256 /* EnumLiteral */ : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -32593,7 +33097,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { var links = getSymbolLinks(symbol); // If symbol being instantiated is itself a instantiation, fetch the original target and combine the // type mappers. This ensures that original type identities are properly preserved and that aliases @@ -33087,29 +33591,27 @@ var ts; type.flags & 131072 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */) || - (source.flags & 65536 /* Union */) !== (target.flags & 65536 /* Union */)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8 /* EnumMember */) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -33120,42 +33622,50 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192 /* Never */) + var s = source.flags; + var t = target.flags; + if (t & 8192 /* Never */) return false; - if (target.flags & 1 /* Any */ || source.flags & 8192 /* Never */) + if (t & 1 /* Any */ || s & 8192 /* Never */) return true; - if (source.flags & 262178 /* StringLike */ && target.flags & 2 /* String */) + if (s & 262178 /* StringLike */ && t & 2 /* String */) return true; - if (source.flags & 340 /* NumberLike */ && target.flags & 4 /* Number */) + if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && + t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) return true; - if (source.flags & 136 /* BooleanLike */ && target.flags & 8 /* Boolean */) + if (s & 84 /* NumberLike */ && t & 4 /* Number */) return true; - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) + if (s & 64 /* NumberLiteral */ && s & 256 /* EnumLiteral */ && + t & 64 /* NumberLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) return true; - if (source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */ && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) return true; - if (source.flags & 2048 /* Undefined */ && (!strictNullChecks || target.flags & (2048 /* Undefined */ | 1024 /* Void */))) + if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 /* Null */ && (!strictNullChecks || target.flags & 4096 /* Null */)) + if (s & 256 /* EnumLiteral */ && t & 256 /* EnumLiteral */) { + if (s & 65536 /* Union */ && t & 65536 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 /* Literal */ && t & 224 /* Literal */ && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 /* Undefined */ && (!strictNullChecks || t & (2048 /* Undefined */ | 1024 /* Void */))) return true; - if (source.flags & 32768 /* Object */ && target.flags & 16777216 /* NonPrimitive */) + if (s & 4096 /* Null */ && (!strictNullChecks || t & 4096 /* Null */)) + return true; + if (s & 32768 /* Object */ && t & 16777216 /* NonPrimitive */) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1 /* Any */) + if (s & 1 /* Any */) return true; - if ((source.flags & 4 /* Number */ | source.flags & 64 /* NumberLiteral */) && target.flags & 272 /* EnumLike */) + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (s & (4 /* Number */ | 64 /* NumberLiteral */) && !(s & 256 /* EnumLiteral */) && (t & 16 /* Enum */ || t & 64 /* NumberLiteral */ && t & 256 /* EnumLiteral */)) return true; - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 256 /* EnumLiteral */ && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 16 /* Enum */ && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -33378,29 +33888,6 @@ var ts; } return 0 /* False */; } - // Check if a property with the given name is known anywhere in the given type. In an object type, a property - // is considered known if the object type is empty and the check is for assignability, if the object type has - // index signatures, or if the property is actually declared in the object type. In a union or intersection - // type, a property is considered known if it is known in any constituent type. - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. - return true; - } - } - else if (type.flags & 196608 /* UnionOrIntersection */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); @@ -33789,10 +34276,10 @@ var ts; } } else if (!(targetProp.flags & 16777216 /* Prototype */)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - if (getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -33901,24 +34388,38 @@ var ts; } var result = -1 /* True */; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - // Only elaborate errors from the first failure - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 /* Instantiated */ && getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We instantiations of the same anonymous type (which typically will be the type of a method). + // Simply do a pairwise comparison of the signatures in the two signature lists instead of the + // much more expensive N * M comparison matrix we explore below. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0 /* False */; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; } - return 0 /* False */; } return result; } @@ -34038,7 +34539,7 @@ var ts; // Invoke the callback for each underlying property symbol of the given symbol and return the first // value that isn't undefined. function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6 /* Synthetic */) { + if (ts.getCheckFlags(prop) & 6 /* Synthetic */) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -34065,13 +34566,13 @@ var ts; } // Return true if source property is a valid override of protected parts of target property. function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is the constructor type for an abstract class @@ -34120,8 +34621,8 @@ var ts; if (sourceProp === targetProp) { return -1 /* True */; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -34215,8 +34716,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -34224,8 +34725,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -34251,7 +34752,7 @@ var ts; return getUnionType(types, /*subtypeReduction*/ true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { // The downfallType/bestSupertypeDownfallType is the first type that caused a particular candidate @@ -34299,27 +34800,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; + return (type.flags & (224 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; } function isLiteralType(type) { return type.flags & 8 /* Boolean */ ? true : - type.flags & 65536 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 /* Union */ ? type.flags & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 /* StringLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } /** @@ -34331,8 +34832,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; @@ -34342,35 +34843,35 @@ var ts; // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { return type.flags & 65536 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 /* StringLiteral */ ? type.text === "" ? 32 /* StringLiteral */ : 0 : - type.flags & 64 /* NumberLiteral */ ? type.text === "0" ? 64 /* NumberLiteral */ : 0 : + type.flags & 32 /* StringLiteral */ ? type.value === "" ? 32 /* StringLiteral */ : 0 : + type.flags & 64 /* NumberLiteral */ ? type.value === 0 ? 64 /* NumberLiteral */ : 0 : type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : type.flags & 7406 /* PossiblyFalsy */; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178 /* StringLike */) - types.push(emptyStringType); - if (flags & 340 /* NumberLike */) - types.push(zeroType); - if (flags & 136 /* BooleanLike */) - types.push(falseType); - if (flags & 1024 /* Void */) - types.push(voidType); - if (flags & 2048 /* Undefined */) - types.push(undefinedType); - if (flags & 4096 /* Null */) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392 /* DefinitelyFalsy */); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 /* String */ ? emptyStringType : + type.flags & 4 /* Number */ ? zeroType : + type.flags & 8 /* Boolean */ || type === falseType ? falseType : + type.flags & (1024 /* Void */ | 2048 /* Undefined */ | 4096 /* Null */) || + type.flags & 32 /* StringLiteral */ && type.value === "" || + type.flags & 64 /* NumberLiteral */ && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 /* Undefined */ | 4096 /* Null */); + return missing === 0 ? type : + missing === 2048 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 4096 /* Null */ ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; } @@ -34537,7 +35038,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { @@ -34622,7 +35123,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864 /* Optional */; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -34655,20 +35156,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -34683,7 +35174,7 @@ var ts; } return; } - if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || + if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 256 /* EnumLiteral */ && target.flags & 256 /* EnumLiteral */) || source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. @@ -34800,26 +35291,29 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768 /* Object */) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + var isNonConstructorObject = target.flags & 32768 /* Object */ && + !(getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -34908,8 +35402,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -35005,7 +35499,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -35018,11 +35512,13 @@ var ts; // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { if (node.kind === 71 /* Identifier */) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99 /* ThisKeyword */) { return "0"; @@ -35091,7 +35587,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); } @@ -35154,8 +35650,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -35173,15 +35669,16 @@ var ts; return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; } if (flags & 32 /* StringLiteral */) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : - type.text === "" ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; + isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : + isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; } if (flags & (4 /* Number */ | 16 /* Enum */)) { return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; } - if (flags & (64 /* NumberLiteral */ | 256 /* EnumLiteral */)) { - var isZero = type.text === "0"; + if (flags & 64 /* NumberLiteral */) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; @@ -35388,7 +35885,7 @@ var ts; } return true; } - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) { + if (source.flags & 256 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -35414,8 +35911,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -35495,8 +35992,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192 /* Never */)) { if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -35527,7 +36024,7 @@ var ts; parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 /* NumberLike */ | 2048 /* Undefined */); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */ | 2048 /* Undefined */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -35553,7 +36050,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -35695,7 +36192,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | 2048 /* Undefined */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */ | 2048 /* Undefined */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -36202,6 +36699,26 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048 /* Undefined */); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 /* PropertyAccessExpression */ || + parent.kind === 181 /* CallExpression */ && parent.expression === node || + parent.kind === 180 /* ElementAccessExpression */ && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144 /* Nullable */); + } + function getDeclaredOrApparentType(symbol, node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -36268,7 +36785,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -36309,7 +36826,7 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048 /* Undefined */); + getNullableType(type, 2048 /* Undefined */); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the @@ -36317,7 +36834,7 @@ var ts; if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -37214,8 +37731,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -37329,7 +37846,7 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340 /* NumberLike */); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84 /* NumberLike */); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -37367,7 +37884,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -37518,6 +38035,8 @@ var ts; 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; } return spread; @@ -37596,6 +38115,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -37613,6 +38136,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); @@ -37622,39 +38148,39 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } // Handle children attribute var parent = openingLikeElement.parent.kind === 249 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that // because then type of children property will have constituent of string type. if (child.kind === 10 /* JsxText */) { @@ -37666,11 +38192,11 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - // Error if there is a attribute named "children" and children element. - // This is because children element will overwrite the value from attributes - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } // If there are children in the body of JSX element, create dummy attribute "children" with anyType so that it will pass the attribute checking process @@ -37681,7 +38207,12 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable @@ -37689,8 +38220,7 @@ var ts; */ function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; - result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag; + result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */; return result; } @@ -37768,7 +38298,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -37820,6 +38361,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072 /* Intersection */) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } /** * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. * Return only attributes type of successfully resolved call signature. @@ -37840,6 +38395,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); @@ -37878,6 +38434,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -37947,7 +38504,7 @@ var ts; // Hello World var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -38152,6 +38709,34 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if the object type is empty and the check is for assignability, if the object type has + * index signatures, or if the property is actually declared in the object type. In a union or intersection + * type, a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & 196608 /* UnionOrIntersection */) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } /** * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" @@ -38180,7 +38765,20 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -38200,29 +38798,11 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149 /* PropertyDeclaration */; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; - } - if (getCheckFlags(s) & 6 /* Synthetic */) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : - checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : - 16 /* Protected */; - var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216 /* Prototype */) { - return 4 /* Public */ | 32 /* Static */; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 /* Method */ || getCheckFlags(symbol) & 4 /* SyntheticMethod */); + return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); } /** * Check whether the requested property access is valid. @@ -38233,11 +38813,11 @@ var ts; * @param prop The symbol for the right hand side of the property access. */ function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 /* PropertyAccessExpression */ || node.kind === 226 /* VariableDeclaration */ ? node.name : node.right; - if (getCheckFlags(prop) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; @@ -38335,42 +38915,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { - if (getCheckFlags(prop) & 1 /* Instantiated */) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -38407,7 +38951,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -38426,6 +38970,126 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455 /* Value */); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 0.3 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + * Names longer than 30 characters don't get suggestions because Levenshtein distance is an n**2 algorithm. + */ + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500 /* ClassMember */) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { + if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 /* PropertyAccessExpression */ ? node.expression @@ -38548,7 +39212,16 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183 /* TaggedTemplateExpression */) { checkExpression(node.template); } @@ -38579,8 +39252,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -38688,7 +39361,7 @@ var ts; // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } // Too many arguments implies incorrect arity. if (!signature.hasRestParameter && argCount > signature.parameters.length) { @@ -39059,7 +39732,7 @@ var ts; case 71 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getLiteralTypeForText(32 /* StringLiteral */, element.name.text); + return getLiteralType(element.name.text); case 144 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { @@ -39169,7 +39842,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183 /* TaggedTemplateExpression */; var isDecorator = node.kind === 147 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -39199,7 +39872,7 @@ var ts; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -39300,7 +39973,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -39308,14 +39981,45 @@ var ts; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information that anySignature. @@ -39323,8 +40027,8 @@ var ts; // declare function f(a: { xa: number; xb: number; }); // f({ | if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -39334,14 +40038,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -39509,7 +40205,7 @@ var ts; // only the class declaration node will have the Abstract flag set. var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128 /* Abstract */) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } // TS 1.0 spec: 4.11 @@ -39676,8 +40372,8 @@ var ts; if (elementType.flags & 65536 /* Union */) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -39854,7 +40550,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048 /* Undefined */); + return getNullableType(type, 2048 /* Undefined */); } } return type; @@ -39920,11 +40616,11 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 /* ObjectBindingPattern */ || - parameter.valueDeclaration.name.kind === 175 /* ArrayBindingPattern */)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -40055,7 +40751,7 @@ var ts; // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. - return (functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + return (functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? createPromiseReturnType(func, widenedType) // Async function : widenedType; // Generator function, AsyncGenerator function, or normal function } @@ -40251,7 +40947,7 @@ var ts; ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = node.type && - ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ ? + ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function if ((functionFlags & 1 /* Generator */) === 0) { @@ -40278,7 +40974,7 @@ var ts; // its return type annotation. var exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } @@ -40291,7 +40987,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -40304,8 +41000,8 @@ var ts; // Get accessors without matching set accessors // Enum members // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) - return !!(getCheckFlags(symbol) & 8 /* Readonly */ || - symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || + symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || symbol.flags & 8 /* EnumMember */); @@ -40392,7 +41088,7 @@ var ts; return silentNeverType; } if (node.operator === 38 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37 /* PlusToken */: @@ -40439,8 +41135,8 @@ var ts; } if (type.flags & 196608 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -40457,8 +41153,8 @@ var ts; } if (type.flags & 65536 /* Union */) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -40467,8 +41163,8 @@ var ts; } if (type.flags & 131072 /* Intersection */) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -40513,7 +41209,7 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 /* NumberLike */ | 512 /* ESSymbol */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 /* NumberLike */ | 512 /* ESSymbol */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) { @@ -40808,7 +41504,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340 /* NumberLike */) && isTypeOfKind(rightType, 340 /* NumberLike */)) { + if (isTypeOfKind(leftType, 84 /* NumberLike */) && isTypeOfKind(rightType, 84 /* NumberLike */)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; @@ -40868,7 +41564,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53 /* AmpersandAmpersandToken */: return getTypeFacts(leftType) & 1048576 /* Truthy */ ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54 /* BarBarToken */: return getTypeFacts(leftType) & 2097152 /* Falsy */ ? @@ -40961,12 +41657,15 @@ var ts; // we are in a yield context. var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2 /* Async */) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 4096 /* AsyncDelegator */); - } + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256 /* Values */); } } @@ -41012,9 +41711,9 @@ var ts; } switch (node.kind) { case 9 /* StringLiteral */: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32 /* StringLiteral */, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101 /* TrueKeyword */: return trueType; case 86 /* FalseKeyword */: @@ -41079,7 +41778,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 /* Literal */ | 262144 /* Index */)); + return maybeTypeOfKind(contextualType, (224 /* Literal */ | 262144 /* Index */)); } return false; } @@ -41424,17 +42123,18 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7 /* InvalidAsyncOrAsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 64 /* Awaiter */); - if (languageVersion < 2 /* ES2015 */) { - checkExternalEmitHelpers(node, 128 /* Generator */); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } - } - if ((functionFlags & 5 /* InvalidGenerator */) === 1 /* Generator */) { - if (functionFlags & 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 2048 /* AsyncGenerator */); + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); } - else if (languageVersion < 2 /* ES2015 */) { + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, 128 /* Generator */); } } @@ -41457,7 +42157,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5 /* InvalidGenerator */) === 1 /* Generator */) { + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -41476,7 +42176,7 @@ var ts; checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } - else if ((functionFlags_1 & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { checkAsyncFunctionReturnType(node); } } @@ -41595,7 +42295,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -41683,7 +42383,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -41840,7 +42541,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 /* Enum */ && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + if (type.flags & 16 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -41883,7 +42584,7 @@ var ts; } // Check if we're indexing with a numeric type and the object type is a generic // type with a constraint that has a numeric index signature. - if (maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && isTypeOfKind(indexType, 340 /* NumberLike */)) { + if (maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && isTypeOfKind(indexType, 84 /* NumberLike */)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1 /* Number */)) { return type; @@ -41943,16 +42644,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1 /* Export */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2 /* Ambient */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 /* Private */ | 16 /* Protected */)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128 /* Abstract */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -41963,7 +42664,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -42087,7 +42788,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -42101,8 +42802,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -42160,12 +42861,13 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -42480,7 +43182,9 @@ var ts; * marked as referenced to prevent import elision. */ function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (rootSymbol @@ -42490,6 +43194,57 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167 /* IntersectionType */: + case 166 /* UnionType */: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168 /* ParenthesizedType */: + return getEntityNameForDecoratorMetadata(node.type); + case 159 /* TypeReference */: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -42520,7 +43275,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -42529,15 +43284,15 @@ var ts; case 154 /* SetAccessor */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149 /* PropertyDeclaration */: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146 /* Parameter */: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -42671,15 +43426,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146 /* Parameter */) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -42759,7 +43515,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -42827,7 +43583,7 @@ var ts; if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { var isDeclaration_1 = node.kind !== 71 /* Identifier */; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -42841,7 +43597,7 @@ var ts; if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { var isDeclaration_2 = node.kind !== 71 /* Identifier */; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -43107,7 +43863,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -43222,11 +43978,14 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216 /* ForOfStatement */) { if (node.awaitModifier) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 8192 /* ForAwaitOfIncludes */); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 5 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); } } @@ -43609,7 +44368,7 @@ var ts; return !!(node.kind === 153 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */))); } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); @@ -43831,13 +44590,16 @@ var ts; } var propDeclaration = prop.valueDeclaration; // index is numeric and property name is not valid numeric literal - if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } // perform property check if property or indexer is declared in 'type' - // this allows to rule out cases when both property and indexer are inherited from the base class + // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 /* BinaryExpression */ || + ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -44076,7 +44838,7 @@ var ts; function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags - return getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; + return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -44109,7 +44871,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { // In order to resolve whether the inherited method was overridden in the base class or not, @@ -44132,15 +44894,11 @@ var ts; } else { // derived overrides base. - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) { // either base or derived property is private - not override, skip it continue; } - if ((baseDeclarationFlags & 32 /* Static */) !== (derivedDeclarationFlags & 32 /* Static */)) { - // value of 'static' is not the same for properties - not override, skip it - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; @@ -44160,7 +44918,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -44247,97 +45005,88 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); - var autoValue = 0; // set to undefined when enum member is non-constant - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); + nodeLinks.flags |= 16384 /* EnumValuesComputed */; + var autoValue = 0; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - // In ambient enum declarations that specify no const modifier, enum member declarations - // that omit a value are considered computed members (as opposed to having auto-incremented values assigned). - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - // If the member declaration specifies no value, the member is considered a constant enum member. - // If the member is the first member in the enum declaration, it is assigned the value zero. - // Otherwise, it is assigned the value of the immediately preceding member plus one, - // and an error occurs if the immediately preceding member is not a constant enum member - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384 /* EnumValuesComputed */; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - // Controls if error should be reported after evaluation of constant value is completed - // Can be false if another more precise error was already reported during evaluation. - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192 /* PrefixUnaryExpression */: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1 /* Literal */) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + // Only here do we need to check that the initializer is assignable to the enum type. + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192 /* PrefixUnaryExpression */: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37 /* PlusToken */: return value_1; case 38 /* MinusToken */: return -value_1; case 52 /* TildeToken */: return ~value_1; } - return undefined; - case 194 /* BinaryExpression */: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194 /* BinaryExpression */: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49 /* BarToken */: return left | right; case 48 /* AmpersandToken */: return left & right; case 46 /* GreaterThanGreaterThanToken */: return left >> right; @@ -44350,81 +45099,53 @@ var ts; case 38 /* MinusToken */: return left - right; case 42 /* PercentToken */: return left % right; } - return undefined; - case 8 /* NumericLiteral */: - checkGrammarNumericLiteral(e); - return +e.text; - case 185 /* ParenthesizedExpression */: - return evalConstant(e.expression); - case 71 /* Identifier */: - case 180 /* ElementAccessExpression */: - case 179 /* PropertyAccessExpression */: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71 /* Identifier */) { - // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. - // instead pick current enum type and later try to fetch member from the type - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9 /* StringLiteral */: + return expr.text; + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185 /* ParenthesizedExpression */: + return evaluate(expr.expression); + case 71 /* Identifier */: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180 /* ElementAccessExpression */: + case 179 /* PropertyAccessExpression */: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = expr.kind === 179 /* PropertyAccessExpression */ ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180 /* ElementAccessExpression */) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9 /* StringLiteral */) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - // expression part in ElementAccess\PropertyAccess should be either identifier or dottedName - var current = expression; - while (current) { - if (current.kind === 71 /* Identifier */) { - break; - } - else if (current.kind === 179 /* PropertyAccessExpression */) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - // allow references to constant members of other enums - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384 /* Enum */))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8 /* EnumMember */)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - // self references are illegal - if (member === propertyDecl) { - return undefined; - } - // illegal case: forward reference - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return 0; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 /* Identifier */ || + node.kind === 179 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 180 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9 /* StringLiteral */; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -44455,7 +45176,7 @@ var ts; // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -44714,6 +45435,10 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + // Don't allow to re-export something with no value side when `--isolatedModules` is set. + if (node.kind === 246 /* ExportSpecifier */ && compilerOptions.isolatedModules && !(target.flags & 107455 /* Value */)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -45436,7 +46161,7 @@ var ts; // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode return getSymbolOfNode(node.parent); } @@ -45564,7 +46289,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -45654,16 +46379,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6 /* Synthetic */) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728 /* Transient */) { if (symbol.leftSpread) { @@ -45981,7 +46706,7 @@ var ts; else if (isTypeOfKind(type, 136 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340 /* NumberLike */)) { + else if (isTypeOfKind(type, 84 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178 /* StringLike */)) { @@ -46010,7 +46735,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096 /* AddUndefined */) { - type = includeFalsyTypes(type, 2048 /* Undefined */); + type = getNullableType(type, 2048 /* Undefined */); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -46022,15 +46747,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -46116,7 +46832,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -46284,7 +46999,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1 /* FirstEmitHelper */; helper <= 8192 /* LastEmitHelper */; helper <<= 1) { + for (var helper = 1 /* FirstEmitHelper */; helper <= 16384 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455 /* Value */); @@ -46311,9 +47026,10 @@ var ts; case 256 /* Values */: return "__values"; case 512 /* Read */: return "__read"; case 1024 /* Spread */: return "__spread"; - case 2048 /* AsyncGenerator */: return "__asyncGenerator"; - case 4096 /* AsyncDelegator */: return "__asyncDelegator"; - case 8192 /* AsyncValues */: return "__asyncValues"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -47419,6 +48135,19 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242 /* ImportSpecifier */: + case 246 /* ExportSpecifier */: + if (name.parent.propertyName) { + return true; + } + // falls through + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); /// /// @@ -47556,53 +48285,63 @@ var ts; if ((kind > 0 /* FirstToken */ && kind <= 142 /* LastToken */) || kind === 169 /* ThisType */) { return node; } - switch (node.kind) { - case 206 /* SemicolonClassElement */: - case 209 /* EmptyStatement */: - case 200 /* OmittedExpression */: - case 225 /* DebuggerStatement */: - case 298 /* EndOfDeclarationMarker */: - case 247 /* MissingDeclaration */: - // No need to visit nodes with no children. - return node; + switch (kind) { // Names + case 71 /* Identifier */: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - // Signatures and Signature Elements - case 160 /* FunctionType */: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161 /* ConstructorType */: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155 /* CallSignature */: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156 /* ConstructSignature */: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150 /* MethodSignature */: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157 /* IndexSignature */: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + // Signature elements + case 145 /* TypeParameter */: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + // Type elements + case 148 /* PropertySignature */: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149 /* PropertyDeclaration */: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150 /* MethodSignature */: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151 /* MethodDeclaration */: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152 /* Constructor */: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153 /* GetAccessor */: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154 /* SetAccessor */: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155 /* CallSignature */: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156 /* ConstructSignature */: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157 /* IndexSignature */: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 159 /* TypeReference */: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 158 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159 /* TypeReference */: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160 /* FunctionType */: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161 /* ConstructorType */: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163 /* TypeLiteral */: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165 /* TupleType */: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166 /* UnionType */: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167 /* IntersectionType */: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170 /* TypeOperator */: @@ -47613,22 +48352,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - // Type Declarations - case 145 /* TypeParameter */: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - // Type members - case 148 /* PropertySignature */: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149 /* PropertyDeclaration */: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151 /* MethodDeclaration */: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152 /* Constructor */: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153 /* GetAccessor */: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154 /* SetAccessor */: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); // Binding patterns case 174 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); @@ -47667,12 +48390,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194 /* BinaryExpression */: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194 /* BinaryExpression */: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196 /* TemplateExpression */: @@ -47689,6 +48412,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204 /* MetaProperty */: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc case 205 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); @@ -47735,6 +48460,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233 /* ModuleDeclaration */: @@ -47743,6 +48472,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236 /* NamespaceExportDeclaration */: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238 /* ImportDeclaration */: @@ -47769,8 +48500,6 @@ var ts; // JSX case 249 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254 /* JsxAttributes */: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251 /* JsxOpeningElement */: @@ -47779,6 +48508,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254 /* JsxAttributes */: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256 /* JsxExpression */: @@ -47808,7 +48539,10 @@ var ts; // Transformation nodes case 296 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297 /* CommaListExpression */: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: + // No need to visit nodes with no children. return node; } } @@ -47884,6 +48618,13 @@ var ts; result = reduceNode(node.expression, cbNode, result); break; // Type member + case 148 /* PropertySignature */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -48234,6 +48975,9 @@ var ts; case 296 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; + case 297 /* CommaListExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -48856,7 +49600,7 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -50275,21 +51019,17 @@ var ts; return ts.createIdentifier("Object"); } function serializeUnionOrIntersectionType(node) { + // Note when updating logic here also update getEntityNameForDecoratorMetadata + // so that aliases can be marked as referenced var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - // If we dont have any other type already set, set the initial type - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { // One of the individual is global object, return immediately return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { // Different types if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || @@ -50819,7 +51559,12 @@ var ts; // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes // old emitter always generate 'expression' part of the name as-is. var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } /** * Transforms the value of an enum member. @@ -50894,10 +51639,12 @@ var ts; * Adds a leading VariableStatement for a enum or module declaration. */ function addVarForEnumOrModuleDeclaration(statements, node) { - // Emit a variable statement for the module. - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + // Emit a variable statement for the module. We emit top-level enums as a `var` + // declaration to avoid static errors in global scripts scripts due to redeclaration. + // enums in any other scope are emitted as a `let` declaration. + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ]); + ], currentScope.kind === 265 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -51154,7 +51901,7 @@ var ts; function visitExportDeclaration(node) { if (!node.exportClause) { // Elide a star export if the module it references does not export a value. - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { // Elide the export declaration if it does not export a value. @@ -51583,7 +52330,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -51920,7 +52667,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -51988,21 +52735,15 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield( - /*asteriskToken*/ undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), /*location*/ node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -52152,6 +52893,9 @@ var ts; return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } + function awaitAsYield(expression) { + return ts.createYield(/*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -52159,24 +52903,21 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); - var values = createAsyncValuesHelper(context, expression, /*location*/ node.expression); - var next = ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), - ts.createVariableDeclaration(result, /*type*/ undefined, next) + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), - /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), - /*incrementor*/ ts.createAssignment(result, next), - /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), + /*condition*/ ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue))), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -52187,13 +52928,7 @@ var ts; ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1 /* SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -52479,12 +53214,22 @@ var ts; /*typeArguments*/ undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); // Mark this node as originally an async function (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; @@ -52498,11 +53243,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), /*typeArguments*/ undefined, [expression]), location); } @@ -52532,7 +53277,7 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -53017,7 +53762,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -53224,7 +53969,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -54502,12 +55247,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26 /* CommaToken */, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { // none of declarations has initializer - the entire variable statement can be deleted @@ -55842,7 +56588,7 @@ var ts; if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -56276,8 +57022,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; } currentSourceFile = node; @@ -58730,7 +59475,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -59025,9 +59770,9 @@ var ts; return visitFunctionDeclaration(node); case 229 /* ClassDeclaration */: return visitClassDeclaration(node); - case 297 /* MergeDeclarationMarker */: + case 298 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 299 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: // This visitor does not descend into the tree, as export/import statements @@ -59826,9 +60571,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -60716,9 +61459,9 @@ var ts; return visitCatchClause(node); case 207 /* Block */: return visitBlock(node); - case 297 /* MergeDeclarationMarker */: + case 298 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 299 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -61200,7 +61943,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -61363,7 +62106,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299 /* Count */); + var enabledSyntaxKindFeatures = new Array(300 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -61428,7 +62171,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } /** * Enables expression substitutions in the pretty printer for the provided SyntaxKind. @@ -62377,7 +63120,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; // Contains the reference paths that needs to go in the declaration file. @@ -62413,11 +63156,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -62844,12 +63587,11 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComents*/ true); emitLines(node.statements); } - // Return a temp variable name to be used in `export default` statements. + // Return a temp variable name to be used in `export default`/`export class ... extends` statements. // The temp name will be of the form _default_counter. // Note that export default is only allowed at most once in a module, so we // do not need to keep track of created temp names. - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -62862,24 +63604,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - // Expression - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -62891,12 +63639,6 @@ var ts; // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -62969,7 +63711,7 @@ var ts; if (modifiers & 512 /* Default */) { write("default "); } - else if (node.kind !== 230 /* InterfaceDeclaration */ && !noDeclare) { + else if (node.kind !== 230 /* InterfaceDeclaration */ && needsDeclare) { write("declare "); } } @@ -63206,7 +63948,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -63305,7 +64047,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -63317,12 +64059,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named @@ -63339,7 +64075,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -63354,6 +64090,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 /* NullKeyword */ ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233 /* ModuleDeclaration */; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128 /* Abstract */)) { @@ -63361,15 +64110,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); write(" {"); writeLine(); increaseIndent(); @@ -63390,7 +64146,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, /*isImplementsList*/ false); + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); } write(" {"); writeLine(); @@ -63449,7 +64205,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */) { + else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */ || + (node.kind === 146 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -63458,7 +64215,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.kind === 229 /* ClassDeclaration */ || node.kind === 146 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -63668,6 +64425,11 @@ var ts; write("["); } else { + if (node.kind === 152 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { + write("();"); + writeLine(); + return; + } // Construct signature or constructor type write new Signature if (node.kind === 156 /* ConstructSignature */ || node.kind === 161 /* ConstructorType */) { write("new "); @@ -63974,7 +64736,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { // Declaration file, use declaration file name declFileName = referencedFile.fileName; } @@ -64158,7 +64920,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -64195,7 +64957,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -64283,7 +65045,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -64362,7 +65126,7 @@ var ts; // Strict mode reserved words // Contextual keywords if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -64580,7 +65344,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -64603,7 +65367,7 @@ var ts; case 97 /* SuperKeyword */: case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: - writeTokenText(kind); + writeTokenNode(node); return; // Expressions case 177 /* ArrayLiteralExpression */: @@ -64668,6 +65432,8 @@ var ts; // Transformation nodes case 296 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); + case 297 /* CommaListExpression */: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -64706,6 +65472,7 @@ var ts; // function emitIdentifier(node) { write(getTextOfNode(node, /*includeTrivia*/ false)); + emitTypeArguments(node, node.typeArguments); } // // Names @@ -64734,6 +65501,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -64854,7 +65622,10 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65 /* TypeLiteralMembers */); + // If the literal is empty, do not add spaces between braces. + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */); + } write("}"); } function emitArrayType(node) { @@ -64892,9 +65663,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1 /* SingleLine */) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -64905,8 +65682,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1 /* SingleLine */) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -64922,7 +65704,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432 /* ObjectBindingPatternElements */); + emitList(node, elements, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 272 /* ObjectBindingPatternElements */ : 432 /* ObjectBindingPatternElementsWithSpaceBetweenBraces */); write("}"); } } @@ -65006,7 +65788,7 @@ var ts; // check if constant enum value is integer var constantValue = ts.getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -65109,7 +65891,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -65837,6 +66619,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272 /* CommaListElements */); + } /** * Emits any prologue directives at the start of a Statement list, returning the * number of prologue directives written to the output. @@ -66118,6 +66903,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -66300,7 +67094,9 @@ var ts; if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -66580,14 +67376,17 @@ var ts; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; @@ -66814,6 +67613,90 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, + // so we'll skip ahead to the second-to-last line. + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + // Output the gutter and the actual contents of the line. + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + // Output the gutter and the error span for the line using tildes. + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -66863,6 +67746,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -66919,7 +67803,8 @@ var ts; // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2 /* Completely */) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); @@ -66978,7 +67863,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -67016,76 +67902,100 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { - // if old program state is not supplied and file does not contain locally defined ambient modules - // then the best we can do is fallback to the default logic + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. return resolveModuleNamesWorker(moduleNames, containingFile); } - // at this point we know that either + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occured during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } + // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules - // OR // - old program state is available - // OR - // - both of items above - // With this it is possible that we can tell how some module names from the initial list will be resolved - // without doing actual resolution (in particular if some name was resolved to ambient module). - // Such names should be excluded from the list of module names that will be provided to `resolveModuleNamesWorker` - // since we don't want to resolve them again. - // this is a list of modules for which we cannot predict resolution so they should be actually resolved + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ var unknownModuleNames; - // this is a list of combined results assembles from predicted and resolved results. - // Order in this list matches the order in the original list of module names `moduleNames` which is important - // so later we can split results to resolutions of modules and resolutions of module augmentations. + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ var result; - // a transient placeholder that is used to mark predicted resolution in the result list + /** A transient placeholder used to mark predicted resolution in the result list. */ var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - // module name is known to be resolved to ambient module if - // - module name is contained in the list of ambient modules that are locally declared in the file - // - in the old program module name was resolved to ambient module whose declaration is in non-modified file + // If we want to reuse resolutions more aggressively, we can refine this to check for whether the + // text of the corresponding modulenames has changed. + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file // (so the same module declaration will land in the new program) - var isKnownToResolveToAmbientModule = false; + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - // found a first module name for which result can be prediced - // this means that this module name should not be passed to `resolveModuleNamesWorker`. - // We'll use a separate list for module names that are definitely unknown. - result = new Array(moduleNames.length); - // copy all module names that appear before the current one in the list - // since they are known to be unknown - unknownModuleNames = moduleNames.slice(0, i); - } - // mark prediced resolution in the result list - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - // found unknown module name and we are already using separate list for those - add it to the list - unknownModuleNames.push(moduleName); + else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - // we've looked throught the list but have not seen any predicted resolution - // use default logic - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; - // combine results of resolutions and predicted results + // Combine results of resolutions and predicted results + if (!result) { + // There were no unresolved/ambient resolutions. + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -67094,16 +68004,15 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { // module used to be resolved to file - ignore it return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -67123,84 +68032,90 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0 /* Not */; } // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); // there is an old program, check if we can reuse its structure var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2 /* Completely */; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { + // The `newSourceFile` object was created for the new program. if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // check tripleslash references if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // check imports and module augmentations collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { // imports has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { // moduleAugmentations has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { // 'types' references has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - // file has no changes - use it as is - newSourceFile = oldSourceFile; - } // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); // try to verify results of module resolution for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -67209,12 +68124,16 @@ var ts; // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - // pass the cache of module/types resolutions from the old source file - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; } // update fileName -> file mapping for (var i = 0; i < newSourceFiles.length; i++) { @@ -67227,8 +68146,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return { @@ -67616,7 +68534,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -67647,7 +68565,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -67694,7 +68611,7 @@ var ts; } break; case 233 /* ModuleDeclaration */: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { var moduleName = node.name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: @@ -67705,7 +68622,7 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { // for global .d.ts files record name of ambient module (ambientModules || (ambientModules = [])).push(moduleName.text); } @@ -67734,45 +68651,52 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -67925,11 +68849,11 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9 /* StringLiteral */; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -67986,7 +68910,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -68084,12 +69008,12 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -68352,6 +69276,7 @@ var ts; "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -69266,57 +70191,37 @@ var ts; * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; + } + if (exclude) { + json.exclude = exclude; + } + if (files) { + json.files = files; + } + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; + } + return options; + })(); + options = ts.extend(existingOptions, options); + options.configFilePath = configFileName; // typingOptions has been deprecated and is only supported for backward compatibility purposes. // It should be removed in future releases - use typeAcquisition instead. var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); - } - if (include && !json["include"]) { - json["include"] = include; - } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; - } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } - options = ts.extend(existingOptions, options); - options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -69326,39 +70231,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - // Merge configs (copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios) - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/ undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -69389,9 +70262,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { // If no includes were specified, exclude common package folders and the outDir excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; @@ -69409,9 +70279,73 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, // Usually a string. + host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -70046,7 +70980,6 @@ var ts; case 148 /* PropertySignature */: case 261 /* PropertyAssignment */: case 262 /* ShorthandPropertyAssignment */: - case 264 /* EnumMember */: case 151 /* MethodDeclaration */: case 150 /* MethodSignature */: case 152 /* Constructor */: @@ -70063,9 +70996,11 @@ var ts; case 231 /* TypeAliasDeclaration */: case 163 /* TypeLiteral */: return 2 /* Type */; + case 264 /* EnumMember */: case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; + case 232 /* EnumDeclaration */: + return 7 /* All */; case 233 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; @@ -70082,7 +71017,7 @@ var ts; case 238 /* ImportDeclaration */: case 243 /* ExportAssignment */: case 244 /* ExportDeclaration */: - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + return 7 /* All */; // An external module can be a Value case 265 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; @@ -70241,7 +71176,7 @@ var ts; case 153 /* GetAccessor */: case 154 /* SetAccessor */: case 233 /* ModuleDeclaration */: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180 /* ElementAccessExpression */: return node.parent.argumentExpression === node; case 144 /* ComputedPropertyName */: @@ -70256,36 +71191,6 @@ var ts; ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; - /** Returns true if the position is within a comment */ - function isInsideComment(sourceFile, token, position) { - // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - // either we are 1. completely inside the comment, or 2. at the end of the comment - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - // is single line comment or just /* - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) { - return true; - } - else { - // is unterminated multi-line comment - return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ && - text.charCodeAt(comment.end - 2) === 42 /* asterisk */); - } - } - return false; - }); - } - } - ts.isInsideComment = isInsideComment; function getContainerNode(node) { while (true) { node = node.parent; @@ -70623,45 +71528,25 @@ var ts; // exit early return current; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1 /* EndOfFileToken */)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } // find the child that contains 'position' - for (var _a = 0, _b = current.getChildren(); _a < _b.length; _a++) { - var child = _b[_a]; - // all jsDocComment nodes were already visited - if (ts.isJSDocNode(child)) { + for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + if (ts.isJSDocNode(child) && !includeJsDocComment) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + continue; + } + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } @@ -70788,10 +71673,6 @@ var ts; return false; } ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, /*predicate*/ undefined); - } - ts.isInComment = isInComment; /** * returns true if the position is in between the open and close elements of an JSX expression. */ @@ -70830,13 +71711,27 @@ var ts; } ts.isInTemplateString = isInTemplateString; /** - * Returns true if the cursor at position in sourceFile is within a comment that additionally - * satisfies predicate, and false otherwise. + * Returns true if the cursor at position in sourceFile is within a comment. + * + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param predicate Additional predicate to test on the comment range. */ - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + function isInComment(sourceFile, position, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position); } + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); + function isInCommentRange(commentRanges) { + return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); + } + } + ts.isInComment = isInComment; + function isPositionInCommentRange(_a, position, text) { + var pos = _a.pos, end = _a.end, kind = _a.kind; + if (pos < position && position < end) { + return true; + } + else if (position === end) { // The end marker of a single-line comment does not include the newline character. // In the following case, we are inside a comment (^ denotes the cursor position): // @@ -70847,16 +71742,14 @@ var ts; // /* asdf */^ // // Internally, we represent the end of the comment at the newline and closing '/', respectively. - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); }); + return kind === 2 /* SingleLineCommentTrivia */ || + // true for unterminated multi-line comment + !(text.charCodeAt(end - 1) === 47 /* slash */ && text.charCodeAt(end - 2) === 42 /* asterisk */); + } + else { + return false; } - return false; } - ts.isInCommentHelper = isInCommentHelper; function hasDocComment(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); // First, we have to see if this position actually landed in a comment. @@ -70979,6 +71872,9 @@ var ts; } ts.isAccessibilityModifier = isAccessibilityModifier; function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } for (var e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { @@ -71027,25 +71923,27 @@ var ts; } ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInNonReferenceComment = isInNonReferenceComment; function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; function isTypeKeyword(kind) { switch (kind) { case 119 /* AnyKeyword */: @@ -71326,8 +72224,8 @@ var ts; // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these // as well var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; diagnostic.start = diagnostic.start - 1; } var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; @@ -71422,7 +72320,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -71431,8 +72329,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -72441,8 +73339,8 @@ var ts; continue; } var start = completePrefix.length; - var length_6 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_6))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -72733,7 +73631,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; if (requestJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; @@ -72763,14 +73661,16 @@ var ts; sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); } - // Add keywords if this is not a member completion list - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + if (hasFilteredClassMemberKeywords) { + ts.addRange(entries, classMemberKeywordCompletions); + } + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; @@ -72826,8 +73726,8 @@ var ts; var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { + var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -72917,10 +73817,11 @@ var ts; function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) { var candidates = []; var entries = []; + var uniques = ts.createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { var candidate = candidates_3[_i]; - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; @@ -72948,9 +73849,10 @@ var ts; } return undefined; } - function addStringLiteralCompletionsFromType(type, result, typeChecker) { + function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 16384 /* TypeParameter */) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; @@ -72958,16 +73860,20 @@ var ts; if (type.flags & 65536 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & 32 /* StringLiteral */) { - result.push({ - name: type.text, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, - sortText: "0" - }); + var name = type.value; + if (!uniques.has(name)) { + uniques.set(name, true); + result.push({ + name: name, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } } } function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { @@ -73032,7 +73938,7 @@ var ts; log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); // Completion not allowed inside comments, bail out if this is the case - var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { @@ -73083,7 +73989,7 @@ var ts; } } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -73171,6 +74077,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; + var hasFilteredClassMemberKeywords = false; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -73204,7 +74111,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols() { // Right of dot member completion list isGlobalCompletion = false; @@ -73255,6 +74162,7 @@ var ts; function tryGetGlobalSymbols() { var objectLikeContainer; var namedImportsOrExports; + var classLikeContainer; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); @@ -73264,6 +74172,11 @@ var ts; // try to show exported member for imported module return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + // cursor inside class declaration + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; + } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; if ((jsxContainer.kind === 250 /* JsxSelfClosingElement */) || (jsxContainer.kind === 251 /* JsxOpeningElement */)) { @@ -73437,16 +74350,16 @@ var ts; function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; - var typeForObject; + var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; - // If the object literal is being assigned to something of type 'null | { hello: string }', - // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 174 /* ObjectBindingPattern */) { @@ -73469,7 +74382,11 @@ var ts; } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = objectLikeContainer.elements; } } @@ -73480,10 +74397,6 @@ var ts; else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); @@ -73525,6 +74438,53 @@ var ts; symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); return true; } + /** + * Aggregates relevant symbols for completion in class declaration + * Relevant symbols are stored in the captured 'symbols' variable. + */ + function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + // We're looking up possible property names from parent type. + isMemberCompletion = true; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for class elements + hasFilteredClassMemberKeywords = true; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); + var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8 /* Private */; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + break; + } + } + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { + var baseClassTypeToGetPropertiesFrom = void 0; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & 32 /* Static */) { + // Use static class to get property symbols from + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32 /* Static */) ? + undefined : + ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + // List of property symbols of base type that are not private and already implemented + symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + } + } + } /** * Returns the immediate owning object literal or binding pattern of a context token, * on the condition that one exists and that the context implies completion should be given. @@ -73561,6 +74521,44 @@ var ts; } return undefined; } + function isFromClassElementDeclaration(node) { + return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetClassLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 17 /* OpenBraceToken */: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + // class c {getValue(): number; | } + case 26 /* CommaToken */: + case 25 /* SemicolonToken */: + // class c { method() { } | } + case 18 /* CloseBraceToken */: + if (ts.isClassLike(location)) { + return location; + } + break; + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent; + } + } + } + // class c { method() { } | method2() { } } + if (location && location.kind === 294 /* SyntaxList */ && ts.isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -73673,7 +74671,7 @@ var ts; containingNodeKind === 231 /* TypeAliasDeclaration */ || isFunction(containingNodeKind); case 115 /* StaticKeyword */: - return containingNodeKind === 149 /* PropertyDeclaration */; + return containingNodeKind === 149 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); case 24 /* DotDotDotToken */: return containingNodeKind === 146 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && @@ -73686,13 +74684,17 @@ var ts; return containingNodeKind === 242 /* ImportSpecifier */ || containingNodeKind === 246 /* ExportSpecifier */ || containingNodeKind === 240 /* NamespaceImport */; + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } + // falls through case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: case 89 /* FunctionKeyword */: case 104 /* VarKeyword */: - case 125 /* GetKeyword */: - case 135 /* SetKeyword */: case 91 /* ImportKeyword */: case 110 /* LetKeyword */: case 76 /* ConstKeyword */: @@ -73700,6 +74702,12 @@ var ts; case 138 /* TypeKeyword */: return true; } + // If the previous token is keyword correspoding to class member completion keyword + // there will be completion available here + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } // Previous token may have been a keyword that was converted to an identifier. switch (contextToken.getText()) { case "abstract": @@ -73742,7 +74750,7 @@ var ts; for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; @@ -73776,7 +74784,7 @@ var ts; continue; } // If this is the current item we are editing right now, do not filter it out - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; @@ -73790,12 +74798,55 @@ var ts; // TODO(jfreeman): Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); } + /** + * Filters out completion suggestions for class elements. + * + * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags + */ + function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 149 /* PropertyDeclaration */ && + m.kind !== 151 /* MethodDeclaration */ && + m.kind !== 153 /* GetAccessor */ && + m.kind !== 154 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + // Dont filter member even if the name matches if it is declared private in the list + if (ts.hasModifier(m, 8 /* Private */)) { + continue; + } + // do not filter it out if the static presence doesnt match + var mIsStatic = ts.hasModifier(m, 32 /* Static */); + var currentElementIsStatic = !!(currentClassElementModifierFlags & 32 /* Static */); + if ((mIsStatic && !currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return ts.concatenate(ts.filter(baseSymbols, function (baseProperty) { return isValidProperty(baseProperty, 8 /* Private */); }), ts.filter(implementingTypeSymbols, function (implementingProperty) { return isValidProperty(implementingProperty, 24 /* NonPublicAccessibilityModifier */); })); + function isValidProperty(propertySymbol, inValidModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } + } /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. * @@ -73807,7 +74858,7 @@ var ts; for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; // If this is the current item we are editing right now, do not filter it out - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253 /* JsxAttribute */) { @@ -73816,6 +74867,9 @@ var ts; } return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); } + function isCurrentlyEditingNode(node) { + return node.getStart() <= position && position <= node.getEnd(); + } } /** * Get the name to be display in completion from a given symbol. @@ -73868,6 +74922,27 @@ var ts; sortText: "0" }); } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 113 /* ProtectedKeyword */: + case 112 /* PrivateKeyword */: + case 117 /* AbstractKeyword */: + case 115 /* StaticKeyword */: + case 123 /* ConstructorKeyword */: + case 131 /* ReadonlyKeyword */: + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + case 120 /* AsyncKeyword */: + return true; + } + } + function isClassMemberCompletionKeywordText(text) { + return isClassMemberCompletionKeyword(ts.stringToToken(text)); + } + var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { + return isClassMemberCompletionKeywordText(entry.name); + }); function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -73884,9 +74959,9 @@ var ts; (function (ts) { var DocumentHighlights; (function (DocumentHighlights) { - function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) { + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -73898,8 +74973,8 @@ var ts; kind: ts.HighlightSpanKind.none }; } - function getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -74693,6 +75768,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { @@ -74771,11 +75849,42 @@ var ts; } }); } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 265 /* SourceFile */) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -74799,7 +75908,7 @@ var ts; } /** Calls `action` for each import, re-export, or require() in a file. */ function forEachImport(sourceFile, action) { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); @@ -74827,26 +75936,20 @@ var ts; } } }); - if (sourceFile.flags & 65536 /* JavaScriptFile */) { - // Find all 'require()' calls. - sourceFile.forEachChild(function recur(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - action(node, node.arguments[0]); - } - else { - node.forEachChild(recur); - } - }); - } } } function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; - if (decl.kind === 238 /* ImportDeclaration */ || decl.kind === 244 /* ExportDeclaration */) { - return decl; + switch (decl.kind) { + case 181 /* CallExpression */: + case 238 /* ImportDeclaration */: + case 244 /* ExportDeclaration */: + return decl; + case 248 /* ExternalModuleReference */: + return decl.parent; + default: + ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); } - ts.Debug.assert(decl.kind === 248 /* ExternalModuleReference */); - return decl.parent; } /** * Given a local reference, we might notice that it's an import/export and recursively search for references of that. @@ -74983,12 +76086,13 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + return ts.forEach(symbol.declarations, function (decl) { + if (ts.isExportAssignment(decl)) { + return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + } + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 /* Identifier */ && name.text; }); - ts.Debug.assert(!!name); - return name; } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { @@ -75035,12 +76139,13 @@ var ts; return { type: "node", node: node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; - function findReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } var out = []; + var checker = program.getTypeChecker(); for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. @@ -75051,44 +76156,46 @@ var ts; return out; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; - function getImplementationsAtPosition(checker, cancellationToken, sourceFiles, sourceFile, position) { + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(typeChecker, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 262 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(checker, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { + var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options) { + function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -75098,10 +76205,6 @@ var ts; switch (def.type) { case "symbol": { var symbol = def.symbol, node_2 = def.node; - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; @@ -75242,7 +76345,7 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } if (node.kind === 265 /* SourceFile */) { return undefined; @@ -75253,6 +76356,7 @@ var ts; return special; } } + var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); // Could not find a symbol e.g. unknown identifier if (!symbol) { @@ -75263,13 +76367,60 @@ var ts; // Can't have references to something that we have no symbol for. return undefined; } - // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; + if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleReferenceLocation(node) { + if (node.kind !== 9 /* StringLiteral */) { + return false; + } + switch (node.parent.kind) { + case 233 /* ModuleDeclaration */: + case 248 /* ExternalModuleReference */: + case 238 /* ImportDeclaration */: + case 244 /* ExportDeclaration */: + return true; + case 181 /* CallExpression */: + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false); + default: + return false; + } + } + function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 265 /* SourceFile */: + // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) + break; + case 233 /* ModuleDeclaration */: + references.push({ type: "node", node: decl.name }); + break; + default: + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + return [{ + definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, + references: references + }]; + } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { @@ -75510,7 +76661,11 @@ var ts; // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.) return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + if (container === void 0) { container = sourceFile; } + if (fullStart === void 0) { fullStart = false; } + var start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + var end = container.getEnd(); var positions = []; /// TODO: Cache symbol existence for files to save text search // Also, need to make this work for unicode escapes. @@ -75542,16 +76697,12 @@ var ts; var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { var position = possiblePositions_1[_i]; var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } // Only pick labels that are either the target label, or have a target that is the target label - if (node === targetLabel || - (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } } @@ -75561,28 +76712,27 @@ var ts; // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node && node.kind) { case 71 /* Identifier */: - return node.getWidth() === searchSymbolName.length; + return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; case 9 /* StringLiteral */: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - // For string literals we have two additional chars for the quotes - node.getWidth() === searchSymbolName.length + 2; + node.text.length === searchSymbolName.length; case 8 /* NumericLiteral */: - return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; default: return false; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); @@ -75604,10 +76754,8 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - var start = state.findInComments ? container.getFullStart() : container.getStart(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments); _i < _a.length; _i++) { + var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } @@ -75738,7 +76886,7 @@ var ts; * position of property accessing, the referenceEntry of such position will be handled in the first case. */ if (!(flags & 134217728 /* Transient */) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -76004,9 +77152,9 @@ var ts; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { - var position = possiblePositions_4[_i]; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); + for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { + var position = possiblePositions_3[_i]; var node = ts.getTouchingWord(sourceFile, position); if (!node || node.kind !== 97 /* SuperKeyword */) { continue; @@ -76058,13 +77206,13 @@ var ts; if (searchSpaceNode.kind === 265 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ @@ -76110,10 +77258,10 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } return [{ @@ -76121,8 +77269,8 @@ var ts; references: references }]; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { - for (var _i = 0, possiblePositions_5 = possiblePositions; _i < possiblePositions_5.length; _i++) { - var position = possiblePositions_5[_i]; + for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { + var position = possiblePositions_4[_i]; var node_7 = ts.getTouchingWord(sourceFile, position); if (node_7 && node_7.kind === 9 /* StringLiteral */ && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, /*isInString*/ true)); @@ -76319,20 +77467,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_5 = []; + var result_6 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -76501,17 +77649,10 @@ var ts; // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. - if (symbol.flags & 8388608 /* Alias */) { - var declaration = symbol.declarations[0]; - // Go to the original declaration for cases: - // - // (1) when the aliased symbol was declared in the location(parent). - // (2) when the aliased symbol is originating from a named import. - // - if (node.kind === 71 /* Identifier */ && - (node.parent === declaration || - (declaration.kind === 242 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 241 /* NamedImports */))) { - symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.flags & 8388608 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; } } // Because name in short-hand property assignment has two different meanings: property name and property value, @@ -76530,16 +77671,6 @@ var ts; var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } - if (ts.isJsxOpeningLikeElement(node.parent)) { - // If there are errors when trying to figure out stateless component function, just return the first declaration - // For example: - // declare function /*firstSource*/MainButton(buttonProps: ButtonProps): JSX.Element; - // declare function /*secondSource*/MainButton(linkProps: LinkProps): JSX.Element; - // declare function /*thirdSource*/MainButton(props: ButtonProps | LinkProps): JSX.Element; - // let opt =
; // Error - We get undefined for resolved signature indicating an error, then just return the first declaration - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } // If the current location we want to find its definition is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. // For example @@ -76550,16 +77681,10 @@ var ts; // function Foo(arg: Props) {} // Foo( { pr/*1*/op1: 10, prop2: true }) var element = ts.getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent)) { - var result = []; - var propertySymbols = ts.getPropertySymbolsFromContextualType(typeChecker, element); - for (var _i = 0, propertySymbols_1 = propertySymbols; _i < propertySymbols_1.length; _i++) { - var propertySymbol = propertySymbols_1[_i]; - result.push.apply(result, getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent)) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); } return getDefinitionFromSymbol(typeChecker, symbol, node); } @@ -76579,13 +77704,13 @@ var ts; return undefined; } if (type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_6 = []; + var result_7 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(/*to*/ result_7, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_6; + return result_7; } if (!type.symbol) { return undefined; @@ -76593,6 +77718,28 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from an import. + // + function shouldSkipAlias(node, declaration) { + if (node.kind !== 71 /* Identifier */) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 239 /* ImportClause */: + case 237 /* ImportEqualsDeclaration */: + return true; + case 242 /* ImportSpecifier */: + return declaration.parent.kind === 241 /* NamedImports */; + default: + return false; + } + } function getDefinitionFromSymbol(typeChecker, symbol, node) { var result = []; var declarations = symbol.getDeclarations(); @@ -76663,7 +77810,7 @@ var ts; } /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { @@ -76691,7 +77838,7 @@ var ts; function findReferenceInPosition(refs, pos) { for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } @@ -76763,6 +77910,7 @@ var ts; "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -76773,8 +77921,6 @@ var ts; "throws", "type", "typedef", - "property", - "prop", "version" ]; var jsDocTagNameCompletionEntries; @@ -77257,8 +78403,8 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_4(sourceFile); } // Remove imports when the imported declaration is already in the list and has the same name. @@ -77301,17 +78447,20 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); + } + else { + // Don't know how to add this. + return false; + } } } return true; @@ -77340,8 +78489,9 @@ var ts; var containers = []; // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -77379,6 +78529,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -77388,8 +78539,8 @@ var ts; fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -77641,8 +78792,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { // Anonymous items are never merged. return true; @@ -77731,9 +78882,9 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186 /* FunctionExpression */: @@ -77750,7 +78901,7 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -79128,138 +80279,6 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - // A partially written generic type expression is not guaranteed to have the correct syntax tree. the expression could be parsed as less than/greater than expression or a comma expression - // or some other combination depending on what the user has typed so far. For the purposes of signature help we need to consider any location after "<" as a possible generic type reference. - // To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it - // will return the generic identifier that started the expression (e.g. "foo" in "foo= 0; - }; - return TokenRangeAccess; - }()); - Shared.TokenRangeAccess = TokenRangeAccess; + var allTokens = []; + for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { + allTokens.push(token); + } var TokenValuesAccess = (function () { - function TokenValuesAccess(tks) { - this.tokens = tks && tks.length ? tks : []; + function TokenValuesAccess(tokens) { + if (tokens === void 0) { tokens = []; } + this.tokens = tokens; } TokenValuesAccess.prototype.GetTokens = function () { return this.tokens; @@ -81588,9 +82634,9 @@ var ts; TokenValuesAccess.prototype.Contains = function (token) { return this.tokens.indexOf(token) >= 0; }; + TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { this.token = token; @@ -81601,18 +82647,14 @@ var ts; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { return tokenValue === this.token; }; + TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { - var result = []; - for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { - result.push(token); - } - return result; + return allTokens; }; TokenAllAccess.prototype.Contains = function () { return true; @@ -81620,51 +82662,80 @@ var ts; TokenAllAccess.prototype.toString = function () { return "[allTokens]"; }; + TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - Shared.TokenAllAccess = TokenAllAccess; - var TokenRange = (function () { - function TokenRange(tokenAccess) { - this.tokenAccess = tokenAccess; + var TokenAllExceptAccess = (function () { + function TokenAllExceptAccess(except) { + this.except = except; } - TokenRange.FromToken = function (token) { - return new TokenRange(new TokenSingleValueAccess(token)); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - TokenRange.FromRange = function (f, to, except) { - if (except === void 0) { except = []; } - return new TokenRange(new TokenRangeAccess(f, to, except)); - }; - TokenRange.AllTokens = function () { - return new TokenRange(new TokenAllAccess()); - }; - TokenRange.prototype.GetTokens = function () { - return this.tokenAccess.GetTokens(); - }; - TokenRange.prototype.Contains = function (token) { - return this.tokenAccess.Contains(token); - }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); - }; - return TokenRange; + TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; + return TokenAllExceptAccess; }()); - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); - TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]); - TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */]); - Shared.TokenRange = TokenRange; + var TokenRange; + (function (TokenRange) { + function FromToken(token) { + return new TokenSingleValueAccess(token); + } + TokenRange.FromToken = FromToken; + function FromTokens(tokens) { + return new TokenValuesAccess(tokens); + } + TokenRange.FromTokens = FromTokens; + function FromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); + } + TokenRange.FromRange = FromRange; + function AnyExcept(token) { + return new TokenAllExceptAccess(token); + } + TokenRange.AnyExcept = AnyExcept; + TokenRange.Any = new TokenAllAccess(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3 /* MultiLineCommentTrivia */])); + TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); + TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ + 92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */ + ]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ + 43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */ + ]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ + 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, + 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ + ]); + TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); + TokenRange.TypeNames = TokenRange.FromTokens([ + 71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, + 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */ + ]); + })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -81689,6 +82760,8 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); + var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + this.rulesMap = formatting.RulesMap.create(activeRules); } RulesProvider.prototype.getRuleName = function (rule) { return this.globalRules.getRuleName(rule); @@ -81704,123 +82777,9 @@ var ts; }; RulesProvider.prototype.ensureUpToDate = function (options) { if (!this.options || !ts.compareDataObjects(this.options, options)) { - var activeRules = this.createActiveRules(options); - var rulesMap = formatting.RulesMap.create(activeRules); - this.activeRules = activeRules; - this.rulesMap = rulesMap; this.options = ts.clone(options); } }; - RulesProvider.prototype.createActiveRules = function (options) { - var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterConstructor) { - rules.push(this.globalRules.SpaceAfterConstructor); - } - else { - rules.push(this.globalRules.NoSpaceAfterConstructor); - } - if (options.insertSpaceAfterCommaDelimiter) { - rules.push(this.globalRules.SpaceAfterComma); - } - else { - rules.push(this.globalRules.NoSpaceAfterComma); - } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { - rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); - } - else { - rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); - } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { - rules.push(this.globalRules.SpaceAfterKeywordInControl); - } - else { - rules.push(this.globalRules.NoSpaceAfterKeywordInControl); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { - rules.push(this.globalRules.SpaceAfterOpenParen); - rules.push(this.globalRules.SpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenParen); - rules.push(this.globalRules.NoSpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { - rules.push(this.globalRules.SpaceAfterOpenBracket); - rules.push(this.globalRules.SpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBracket); - rules.push(this.globalRules.NoSpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true - // so if the option is undefined, we should treat it as true as well - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { - rules.push(this.globalRules.SpaceAfterOpenBrace); - rules.push(this.globalRules.SpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBrace); - rules.push(this.globalRules.NoSpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { - rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); - } - else { - rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { - rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); - } - if (options.insertSpaceAfterSemicolonInForStatements) { - rules.push(this.globalRules.SpaceAfterSemicolonInFor); - } - else { - rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); - } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { - rules.push(this.globalRules.SpaceBeforeBinaryOperator); - rules.push(this.globalRules.SpaceAfterBinaryOperator); - } - else { - rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); - rules.push(this.globalRules.NoSpaceAfterBinaryOperator); - } - if (options.insertSpaceBeforeFunctionParenthesis) { - rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl); - } - else { - rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl); - } - if (options.placeOpenBraceOnNewLineForControlBlocks) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); - } - if (options.placeOpenBraceOnNewLineForFunctions) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); - rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); - } - if (options.insertSpaceAfterTypeAssertion) { - rules.push(this.globalRules.SpaceAfterTypeAssertion); - } - else { - rules.push(this.globalRules.NoSpaceAfterTypeAssertion); - } - rules = rules.concat(this.globalRules.LowPriorityCommonRules); - return rules; - }; return RulesProvider; }()); formatting.RulesProvider = RulesProvider; @@ -82074,7 +83033,7 @@ var ts; } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { // formatting context is used by rules provider - var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRangeHasError; var previousRange; var previousParent; @@ -82171,7 +83130,7 @@ var ts; // falls through case 149 /* PropertyDeclaration */: case 146 /* Parameter */: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -83069,9 +84028,7 @@ var ts; if (node.kind === 20 /* CloseParenToken */) { return -1 /* Unknown */; } - if (node.parent && (node.parent.kind === 181 /* CallExpression */ || - node.parent.kind === 182 /* NewExpression */) && - node.parent.expression !== node) { + if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { @@ -83665,7 +84622,7 @@ var ts; }()); textChanges.ChangeTracker = ChangeTracker; function getNonformattedText(node, sourceFile, newLine) { - var options = { newLine: newLine, target: sourceFile.languageVersion }; + var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); printer.writeNode(3 /* Unspecified */, node, sourceFile, writer); @@ -83694,27 +84651,8 @@ var ts; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } - var nullTransformationContext = { - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: function () { return undefined; }, - getCompilerOptions: ts.notImplemented, - getEmitHost: ts.notImplemented, - getEmitResolver: ts.notImplemented, - hoistFunctionDeclaration: ts.noop, - hoistVariableDeclaration: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop - }; function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // create proxy node for non synthesized nodes var newNode = ts.nodeIsSynthesized(visited) ? visited @@ -83759,6 +84697,16 @@ var ts; setEnd(nodes, _this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; } Writer.prototype.setLastNonTriviaPosition = function (s, force) { if (force || !isTrivia(s)) { @@ -83827,14 +84775,14 @@ var ts; var codefix; (function (codefix) { var codeFixes = []; - function registerCodeFix(action) { - ts.forEach(action.errorCodes, function (error) { + function registerCodeFix(codeFix) { + ts.forEach(codeFix.errorCodes, function (error) { var fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } codefix.registerCodeFix = registerCodeFix; @@ -83858,6 +84806,51 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + // A map with the refactor code as key, the refactor itself as value + // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want + var refactors = ts.createMap(); + function registerRefactor(refactor) { + refactors.set(refactor.name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + var results; + var refactorList = []; + refactors.forEach(function (refactor) { + refactorList.push(refactor); + }); + for (var _i = 0, refactorList_1 = refactorList; _i < refactorList_1.length; _i++) { + var refactor_2 = refactorList_1[_i]; + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor_2.isApplicable(context)) { + (results || (results = [])).push({ name: refactor_2.name, description: refactor_2.description }); + } + } + return results; + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getRefactorCodeActions(context, refactorName) { + var result; + var refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + var codeActions = refactor.getCodeActions(context); + if (codeActions) { + ts.addRange((result || (result = [])), codeActions); + } + return result; + } + refactor_1.getRefactorCodeActions = getRefactorCodeActions; + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -83924,7 +84917,8 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { @@ -84014,7 +85008,7 @@ var ts; /*dotDotDotToken*/ undefined, "x", /*questionToken*/ undefined, stringTypeNode, /*initializer*/ undefined); - var indexSignature = ts.createIndexSignatureDeclaration( + var indexSignature = ts.createIndexSignature( /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); @@ -84031,6 +85025,60 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + function getActionsForCorrectSpelling(context) { + var sourceFile = context.sourceFile; + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + var node = ts.getTokenAtPosition(sourceFile, context.span.start); + var checker = context.program.getTypeChecker(); + var suggestion; + if (node.kind === 71 /* Identifier */ && ts.isPropertyAccessExpression(node.parent)) { + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else { + var meaning = ts.getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4 /* Namespace */) { + flags |= 1920 /* Namespace */; + } + if (meaning & 2 /* Type */) { + flags |= 793064 /* Type */; + } + if (meaning & 1 /* Value */) { + flags |= 107455 /* Value */; + } + return flags; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -84232,131 +85280,135 @@ var ts; } switch (token.kind) { case 71 /* Identifier */: - switch (token.parent.kind) { - case 226 /* VariableDeclaration */: - switch (token.parent.parent.parent.kind) { - case 214 /* ForStatement */: - var forStatement = token.parent.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(token.parent); - } - case 216 /* ForOfStatement */: - var forOfStatement = token.parent.parent.parent; - if (forOfStatement.initializer.kind === 227 /* VariableDeclarationList */) { - var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); - } - break; - case 215 /* ForInStatement */: - // There is no valid fix in the case of: - // for .. in - return undefined; - case 260 /* CatchClause */: - var catchClause = token.parent.parent; - var parameter = catchClause.variableDeclaration.getChildren()[0]; - return deleteNode(parameter); - default: - var variableStatement = token.parent.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); - } - else { - return deleteNodeInList(token.parent); - } - } - // TODO: #14885 - // falls through - case 145 /* TypeParameter */: - var typeParameters = token.parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); - if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { - return deleteRange(typeParameters); - } - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); - if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); - } - else { - return deleteNodeInList(token.parent); - } - case 146 /* Parameter */: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } - // handle case where 'import a = A;' - case 237 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); - return deleteNode(importEquals); - case 242 /* ImportSpecifier */: - var namedImports = token.parent.parent; - if (namedImports.elements.length === 1) { - // Only 1 import and it is unused. So the entire declaration should be removed. - var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); - return deleteNode(importSpec); - } - else { - // delete import specifier - return deleteNodeInList(token.parent); - } - // handle case where "import d, * as ns from './file'" - // or "'import {a, b as ns} from './file'" - case 239 /* ImportClause */: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); - return deleteNode(importDecl); - } - else { - // import |d,| * as ns from './file' - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { - // shift first non-whitespace position after comma to the start position of the node - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); - } - else { - return deleteNode(importClause.name); - } - } - case 240 /* NamespaceImport */: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { - var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); - return deleteNode(importDecl); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); - if (previousToken && previousToken.kind === 26 /* CommaToken */) { - var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); - } - return deleteRange(namespaceImport); - } - } - break; + return deleteIdentifier(); case 149 /* PropertyDeclaration */: case 240 /* NamespaceImport */: return deleteNode(token.parent); + default: + return deleteDefault(); } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + function deleteIdentifier() { + switch (token.parent.kind) { + case 226 /* VariableDeclaration */: + return deleteVariableDeclaration(token.parent); + case 145 /* TypeParameter */: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); + if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { + return deleteRange(typeParameters); + } + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); + if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { + return deleteRange(typeParameters); + } + return deleteNodeRange(previousToken, nextToken); + } + else { + return deleteNodeInList(token.parent); + } + case 146 /* Parameter */: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return deleteNode(token.parent); + } + else { + return deleteNodeInList(token.parent); + } + // handle case where 'import a = A;' + case 237 /* ImportEqualsDeclaration */: + var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); + return deleteNode(importEquals); + case 242 /* ImportSpecifier */: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + // Only 1 import and it is unused. So the entire declaration should be removed. + var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); + return deleteNode(importSpec); + } + else { + // delete import specifier + return deleteNodeInList(token.parent); + } + // handle case where "import d, * as ns from './file'" + // or "'import {a, b as ns} from './file'" + case 239 /* ImportClause */: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); + return deleteNode(importDecl); + } + else { + // import |d,| * as ns from './file' + var start_4 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 26 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); + } + else { + return deleteNode(importClause.name); + } + } + case 240 /* NamespaceImport */: + var namespaceImport = token.parent; + if (namespaceImport.name === token && !namespaceImport.parent.name) { + var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); + return deleteNode(importDecl); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); + if (previousToken && previousToken.kind === 26 /* CommaToken */) { + var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); + return deleteRange({ pos: startPosition, end: namespaceImport.end }); + } + return deleteRange(namespaceImport); + } + default: + return deleteDefault(); + } } - else { - return undefined; + // token.parent is a variableDeclaration + function deleteVariableDeclaration(varDecl) { + switch (varDecl.parent.parent.kind) { + case 214 /* ForStatement */: + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return deleteNode(forInitializer); + } + else { + return deleteNodeInList(varDecl); + } + case 216 /* ForOfStatement */: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 227 /* VariableDeclarationList */); + var forOfInitializer = forOfStatement.initializer; + return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + case 215 /* ForInStatement */: + // There is no valid fix in the case of: + // for .. in + return undefined; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return deleteNode(variableStatement); + } + else { + return deleteNodeInList(varDecl); + } + } } function deleteNode(n) { return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); @@ -84388,6 +85440,15 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ], + getCodeActions: getImportCodeActions + }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; @@ -84485,400 +85546,393 @@ var ts; }; return ImportCodeActionMap; }()); - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - // this is a module id -> module import declaration map - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); - return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true); + function getImportCodeActions(context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + // this is a module id -> module import declaration map + var cachedImportDeclarations = []; + var lastImportDeclaration; + var currentTokenMeaning = ts.getMeaningFromLocation(token); + if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); + return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true); + } + var candidateModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + candidateModules.push(otherSourceFile.symbol); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); + } + for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { + var moduleSymbol = candidateModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); } } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - // check if this symbol is already used - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (cached) { + return cached; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 238 /* ImportDeclaration */) { + return node; } - } - // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); - } - } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + if (node.kind === 237 /* ImportEqualsDeclaration */) { + return node; } + node = node.parent; } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238 /* ImportDeclaration */) { - return node; + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608 /* Alias */) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + // With an existing import statement, there are more than one actions the user can do. + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + if (declaration.kind === 238 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { + // case: + // import * as ns from "foo" + namespaceImportDeclaration = declaration; } - if (node.kind === 237 /* ImportEqualsDeclaration */) { - return node; + else { + // cases: + // import default from "foo" + // import { bar } from "foo" or combination with the first one + // import "foo" + namedImportDeclaration = declaration; } - node = node.parent; + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + // case: + // import foo = require("foo") + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - return undefined; } - } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608 /* Alias */) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); } - return ts.getSymbolId(symbol); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; - } - function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - // With an existing import statement, there are more than one actions the user can do. - return getCodeActionsForExistingImport(existingDeclarations); + if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + /** + * If the existing import declaration already has a named import list, just + * insert the identifier into that list. + */ + var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); } else { - return [getCodeActionForNewImport()]; + // we need to create a new import statement, but the existing module specifier can be reused. + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - // It is possible that multiple import statements with the same specifier exist in the file. - // e.g. - // - // import * as ns from "foo"; - // import { member1, member2 } from "foo"; - // - // member3/**/ <-- cusor here - // - // in this case we should provie 2 actions: - // 1. change "member3" to "ns.member3" - // 2. add "member3" to the second import statement's import list - // and it is up to the user to decide which one fits best. - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; - if (declaration.kind === 238 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { - // case: - // import * as ns from "foo" - namespaceImportDeclaration = declaration; - } - else { - // cases: - // import default from "foo" - // import { bar } from "foo" or combination with the first one - // import "foo" - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - // case: - // import foo = require("foo") - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { + return declaration.moduleReference.expression.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var importList = importClause.namedBindings; + var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); + // case 1: + // original text: import default from "module" + // change to: import default, { name } from "module" + // case 2: + // original text: import {} from "module" + // change to: import { name } from "module" + if (!importList || importList.elements.length === 0) { + var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); + return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - /** - * If the existing import declaration already has a named import list, just - * insert the identifier into that list. - */ - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + /** + * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element + * import { + * foo + * } from "./module"; + */ + return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 238 /* ImportDeclaration */) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); } else { - // we need to create a new import statement, but the existing module specifier can be reused. - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + namespacePrefix = declaration.name.getText(); } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { - return declaration.moduleReference.expression.getText(); + namespacePrefix = ts.stripQuotes(namespacePrefix); + /** + * Cases: + * import * as ns from "mod" + * import default, * as ns from "mod" + * import ns = require("mod") + * + * Because there is no import list, we alter the reference to include the + * namespace instead of altering the import declaration. For example, "foo" would + * become "ns.foo" + */ + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!lastImportDeclaration) { + // insert after any existing imports + for (var i = sourceFile.statements.length - 1; i >= 0; i--) { + var statement = sourceFile.statements[i]; + if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { + lastImportDeclaration = statement; + break; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); - // case 1: - // original text: import default from "module" - // change to: import default, { name } from "module" - // case 2: - // original text: import {} from "module" - // change to: import { name } from "module" - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); - } - /** - * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element - * import { - * foo - * } from "./module"; - */ - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238 /* ImportDeclaration */) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - /** - * Cases: - * import * as ns from "mod" - * import default, * as ns from "mod" - * import ns = require("mod") - * - * Because there is no import list, we alter the reference to include the - * namespace instead of altering the import declaration. For example, "foo" would - * become "ns.foo" - */ - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - // insert after any existing imports - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { - lastImportDeclaration = statement; - break; - } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var changeTracker = createChangeTracker(); + var importClause = isDefault + ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) + : isNamespaceImport + ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(name))) + : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))])); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + if (!lastImportDeclaration) { + changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); + } + // if this file doesn't have any import statements, insert an import statement and then insert a new line + // between the only import statement and user code. Otherwise just insert the statement because chances + // are there are already a new line seperating code and import statements. + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.fileName; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { + return moduleSymbol.name; } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) - : isNamespaceImport - ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))])); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - // if this file doesn't have any import statements, insert an import statement and then insert a new line - // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line seperating code and import statements. - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { - return moduleSymbol.name; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { return undefined; } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); + if (!relativeName) { + return undefined; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { - return undefined; - } - var relativeFileName; - if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { - // if node_modules folder is in this folder or any of its parent folder, no need to keep it. - relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); - } - else { - relativeFileName = getRelativePath(moduleFileName, sourceDirectory); - } - relativeFileName = ts.removeFileExtension(relativeFileName); - if (ts.endsWith(relativeFileName, "/index")) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } - else { - try { - var moduleDirectory = ts.getDirectoryPath(moduleFileName); - var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); - if (packageJsonContent) { - var mainFile = packageJsonContent.main || packageJsonContent.typings; - if (mainFile) { - var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; + } } - catch (e) { } } - return relativeFileName; } + return relativeName; } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); } } return undefined; } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } } - return fileName; } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; - } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + // if node_modules folder is in this folder or any of its parent folder, no need to keep it. + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; } } - } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); - } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = getRelativePathIfInDirectory(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } } } - }); + function createChangeTracker() { + return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + } + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -85010,7 +86064,7 @@ var ts; } var declaration = declarations[0]; // Clone name to remove leading trivia. - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -85068,7 +86122,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -85124,7 +86178,7 @@ var ts; /*returnType*/ undefined); } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethodDeclaration( + return ts.createMethod( /*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } @@ -85147,6 +86201,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /// /// /// @@ -85156,6 +86211,188 @@ var ts; /// /// /// +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions: getCodeActions, + isApplicable: isApplicable + }; + refactor.registerRefactor(convertFunctionToES6Class); + function isApplicable(context) { + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + return symbol && symbol.flags & 16 /* Function */ && symbol.members && symbol.members.size > 0; + } + function getCodeActions(context) { + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + return []; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 228 /* FunctionDeclaration */: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 226 /* VariableDeclaration */: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, /*inList*/ true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return []; + } + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { + var deleteCallback = deletes_1[_i]; + deleteCallback(); + } + return [{ + description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + // Parent node has already been deleted; do nothing + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); + } + else { + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); + } + } + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + // all instance members are stored in the "member" array of symbol + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, /*modifiers*/ undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + // all static members are stored in the "exports" array of symbol + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + // Right now the only thing we can convert are function expressions - other values shouldn't get + // transformed. We can update this once ES public class properties are available. + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + // both properties and methods are bound as property symbols + if (!(symbol.flags & 4 /* Property */)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 /* ExpressionStatement */ + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 186 /* FunctionExpression */: + var functionExpression = assignmentBinaryExpression.right; + return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + case 187 /* ArrowFunction */: + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 207 /* Block */) { + bodyBlock = arrowFunctionBody; + } + else { + var expression = arrowFunctionBody; + bodyBlock = ts.createBlock([ts.createReturn(expression)]); + } + return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + default: + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + return ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 186 /* FunctionExpression */) { + return undefined; + } + if (node.name.kind !== 71 /* Identifier */) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/// /// /// /// @@ -85182,11 +86419,15 @@ var ts; /// /// /// +/// /// +/// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; + /* @internal */ + var ruleProvider; function createNode(kind, pos, end, parent) { var node = kind >= 143 /* FirstNode */ ? new NodeObject(kind, pos, end) : kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : @@ -85571,13 +86812,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_7 !== undefined) { - return result_7; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_8 = getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - var expr = declaration.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var expr = name.expression; if (expr.kind === 179 /* PropertyAccessExpression */) { return expr.name.text; } @@ -85962,7 +87204,7 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - var ruleProvider; + ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -85987,10 +87229,6 @@ var ts; return sourceFile; } function getRuleProvider(options) { - // Ensure rules are initialized and up to date wrt to formatting options - if (!ruleProvider) { - ruleProvider = new ts.formatting.RulesProvider(); - } ruleProvider.ensureUpToDate(options); return ruleProvider; } @@ -86283,7 +87521,7 @@ var ts; /// Goto implementation function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { @@ -86300,7 +87538,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); @@ -86333,11 +87571,11 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { @@ -86640,8 +87878,7 @@ var ts; var matchPosition = matchArray.index + preamble.length; // OK, we have found a match in the file. This is only an acceptable match if // it is contained within a comment. - var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!ts.isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInComment(sourceFile, matchPosition)) { continue; } var descriptor = undefined; @@ -86729,11 +87966,35 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file, positionOrRange, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken: cancellationToken + }; + } + function getApplicableRefactors(fileName, positionOrRange) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getApplicableRefactors: getApplicableRefactors, + getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -86859,20 +88120,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = ts.getTextOfPropertyName(node.name); if (name && contextualType) { - var result_8 = []; + var result_9 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_8.push(symbol); + result_9.push(symbol); } }); - return result_8; + return result_9; } if (symbol) { - result_8.push(symbol); - return result_8; + result_9.push(symbol); + return result_9; } } return undefined; @@ -88130,6 +89391,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations @@ -88304,3 +89568,5 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = "2.4"; + +//# sourceMappingURL=typescriptServices.js.map diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 01d5540db54..df00c45de24 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -359,9 +359,10 @@ declare namespace ts { SyntaxList = 294, NotEmittedStatement = 295, PartiallyEmittedExpression = 296, - MergeDeclarationMarker = 297, - EndOfDeclarationMarker = 298, - Count = 299, + CommaListExpression = 297, + MergeDeclarationMarker = 298, + EndOfDeclarationMarker = 299, + Count = 300, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -474,6 +475,10 @@ declare namespace ts { type ModifiersArray = NodeArray; interface Identifier extends PrimaryExpression { kind: SyntaxKind.Identifier; + /** + * Text of identifier (with escapes converted to characters). + * If the identifier begins with two underscores, this will begin with three. + */ text: string; originalKeywordKind?: SyntaxKind; isInJSDocNamespace?: boolean; @@ -491,9 +496,11 @@ declare namespace ts { type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { name?: DeclarationName; } - interface DeclarationStatement extends Declaration, Statement { + interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { @@ -504,7 +511,7 @@ declare namespace ts { kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } - interface TypeParameterDeclaration extends Declaration { + interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -512,7 +519,7 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends Declaration { + interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -525,7 +532,7 @@ declare namespace ts { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; - interface VariableDeclaration extends Declaration { + interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; @@ -537,7 +544,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends Declaration { + interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -546,7 +553,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface BindingElement extends Declaration { + interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; @@ -568,7 +575,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface ObjectLiteralElement extends Declaration { + interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -590,7 +597,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends Declaration { + interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -598,7 +605,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface PropertyLikeDeclaration extends Declaration { + interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } interface ObjectBindingPattern extends Node { @@ -950,7 +957,7 @@ declare namespace ts { } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - interface PropertyAccessExpression extends MemberExpression, Declaration { + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1016,7 +1023,7 @@ declare namespace ts { } interface MetaProperty extends PrimaryExpression { kind: SyntaxKind.MetaProperty; - keywordToken: SyntaxKind; + keywordToken: SyntaxKind.NewKeyword; name: Identifier; } interface JsxElement extends PrimaryExpression { @@ -1076,6 +1083,13 @@ declare namespace ts { interface NotEmittedStatement extends Statement { kind: SyntaxKind.NotEmittedStatement; } + /** + * A list of comma-seperated expressions. This node is only created by transformations. + */ + interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; + elements: NodeArray; + } interface EmptyStatement extends Statement { kind: SyntaxKind.EmptyStatement; } @@ -1197,7 +1211,7 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - interface ClassLikeDeclaration extends Declaration { + interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1210,11 +1224,11 @@ declare namespace ts { interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { kind: SyntaxKind.ClassExpression; } - interface ClassElement extends Declaration { + interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - interface TypeElement extends Declaration { + interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1238,7 +1252,7 @@ declare namespace ts { typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends Declaration { + interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; @@ -1297,13 +1311,13 @@ declare namespace ts { moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; - interface ImportClause extends Declaration { + interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } - interface NamespaceImport extends Declaration { + interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1330,13 +1344,13 @@ declare namespace ts { elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; - interface ImportSpecifier extends Declaration { + interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; name: Identifier; } - interface ExportSpecifier extends Declaration { + interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; @@ -1467,7 +1481,7 @@ declare namespace ts { kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } - interface JSDocTypedefTag extends JSDocTag, Declaration { + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -1706,11 +1720,11 @@ declare namespace ts { /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; + getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; - getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; @@ -1720,38 +1734,48 @@ declare namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + getContextualType(node: Expression): Type | undefined; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type; + getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; + getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; + getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; } enum NodeBuilderFlags { None = 0, - allowThisInObjectLiteral = 1, - allowQualifedNameInPlaceOfIdentifier = 2, - allowTypeParameterInQualifiedName = 4, - allowAnonymousIdentifier = 8, - allowEmptyUnionOrIntersection = 16, - allowEmptyTuple = 32, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + AllowThisInObjectLiteral = 1024, + AllowQualifedNameInPlaceOfIdentifier = 2048, + AllowAnonymousIdentifier = 8192, + AllowEmptyUnionOrIntersection = 16384, + AllowEmptyTuple = 32768, + IgnoreErrors = 60416, + InObjectTypeLiteral = 1048576, + InTypeAlias = 8388608, } interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1912,18 +1936,18 @@ declare namespace ts { Index = 262144, IndexedAccess = 524288, NonPrimitive = 16777216, - Literal = 480, + Literal = 224, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, StringLike = 262178, - NumberLike = 340, + NumberLike = 84, BooleanLike = 136, EnumLike = 272, UnionOrIntersection = 196608, StructuredType = 229376, StructuredOrTypeVariable = 1032192, TypeVariable = 540672, - Narrowable = 17810431, + Narrowable = 17810175, NotUnionOrUnit = 16810497, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; @@ -1935,15 +1959,17 @@ declare namespace ts { aliasTypeArguments?: Type[]; } interface LiteralType extends Type { - text: string; + value: string | number; freshType?: LiteralType; regularType?: LiteralType; } - interface EnumType extends Type { - memberTypes: EnumLiteralType[]; + interface StringLiteralType extends LiteralType { + value: string; } - interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; + interface NumberLiteralType extends LiteralType { + value: number; + } + interface EnumType extends Type { } enum ObjectFlags { Class = 1, @@ -1988,7 +2014,7 @@ declare namespace ts { */ interface TypeReference extends ObjectType { target: GenericType; - typeArguments: Type[]; + typeArguments?: Type[]; } interface GenericType extends InterfaceType, TypeReference { } @@ -2024,7 +2050,7 @@ declare namespace ts { } interface Signature { declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; + typeParameters?: TypeParameter[]; parameters: Symbol[]; } enum IndexKind { @@ -2059,9 +2085,9 @@ declare namespace ts { next?: DiagnosticMessageChain; } interface Diagnostic { - file: SourceFile; - start: number; - length: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; messageText: string | DiagnosticMessageChain; category: DiagnosticCategory; code: number; @@ -2329,6 +2355,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, + NoAsciiEscaping = 16777216, } interface EmitHelper { readonly name: string; @@ -2611,14 +2638,14 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; /** Optionally, get the shebang */ - function getShebang(text: string): string; + function getShebang(text: string): string | undefined; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; @@ -2709,6 +2736,7 @@ declare namespace ts { function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; + function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; /** Create a unique temporary variable for use in a loop. */ @@ -2727,58 +2755,19 @@ declare namespace ts { function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; - function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): SignatureDeclaration; - function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; - function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; - function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; - function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; - function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; - function createThisTypeNode(): ThisTypeNode; - function createLiteralTypeNode(literal: Expression): LiteralTypeNode; - function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; - function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; - function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; - function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; - function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; - function createTypeQueryNode(exprName: EntityName): TypeQueryNode; - function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; - function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; - function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray): UnionOrIntersectionTypeNode; - function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; - function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; - function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; - function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; - function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; - function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; - function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; - function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; - function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; function createDecorator(expression: Expression): Decorator; function updateDecorator(node: Decorator, expression: Expression): Decorator; + function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; - function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function createConstructor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; @@ -2786,6 +2775,45 @@ declare namespace ts { function updateGetAccessor(node: GetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; function createSetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; function updateSetAccessor(node: SetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; + function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; + function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; + function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; + function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; + function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; + function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; + function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; + function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; + function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; + function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; + function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; + function createTypeQueryNode(exprName: EntityName): TypeQueryNode; + function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; + function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; + function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; + function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; + function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; + function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; + function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; + function createUnionTypeNode(types: TypeNode[]): UnionTypeNode; + function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; + function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode; + function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionTypeNode | IntersectionTypeNode; + function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; + function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; + function createThisTypeNode(): ThisTypeNode; + function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; + function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function createLiteralTypeNode(literal: Expression): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; function createObjectBindingPattern(elements: BindingElement[]): ObjectBindingPattern; function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern; function createArrayBindingPattern(elements: ArrayBindingElement[]): ArrayBindingPattern; @@ -2827,7 +2855,7 @@ declare namespace ts { function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; - function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression; + function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; @@ -2847,16 +2875,15 @@ declare namespace ts { function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; function createNonNullExpression(expression: Expression): NonNullExpression; function updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression; + function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function createSemicolonClassElement(): SemicolonClassElement; function createBlock(statements: Statement[], multiLine?: boolean): Block; function updateBlock(node: Block, statements: Statement[]): Block; function createVariableStatement(modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList | VariableDeclaration[]): VariableStatement; function updateVariableStatement(node: VariableStatement, modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList): VariableStatement; - function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; - function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; - function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; - function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; function createEmptyStatement(): EmptyStatement; function createStatement(expression: Expression): ExpressionStatement; function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; @@ -2888,10 +2915,19 @@ declare namespace ts { function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement; function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function createDebuggerStatement(): DebuggerStatement; + function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; + function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; + function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function createClassDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; + function createInterfaceDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; function createEnumDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, members: EnumMember[]): EnumDeclaration; function updateEnumDeclaration(node: EnumDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, members: EnumMember[]): EnumDeclaration; function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; @@ -2900,6 +2936,8 @@ declare namespace ts { function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock; function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock; function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; + function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function createImportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; @@ -2930,20 +2968,20 @@ declare namespace ts { function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; - function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; - function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; - function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; - function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCaseClause(expression: Expression, statements: Statement[]): CaseClause; function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]): CaseClause; function createDefaultClause(statements: Statement[]): DefaultClause; function updateDefaultClause(node: DefaultClause, statements: Statement[]): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause; function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause; function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; @@ -2976,6 +3014,8 @@ declare namespace ts { */ function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createCommaList(elements: Expression[]): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: Expression[]): CommaListExpression; function createBundle(sourceFiles: SourceFile[]): Bundle; function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; function createComma(left: Expression, right: Expression): Expression; @@ -3040,11 +3080,11 @@ declare namespace ts { /** * Gets the constant value to emit for an expression. */ - function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; /** * Sets the constant value to emit for an expression. */ - function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression; + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression; /** * Adds an EmitHelper to a node. */ @@ -3069,17 +3109,13 @@ declare namespace ts { } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; - function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; function isExternalModule(file: SourceFile): boolean; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - /** Array that is only intended to be pushed to, never read. */ - interface Push { - push(value: T): void; - } function moduleHasNonRelativeName(moduleName: string): boolean; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; @@ -3218,6 +3254,7 @@ declare namespace ts { getNewLine(): string; } function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } @@ -3246,9 +3283,10 @@ declare namespace ts { * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine; - function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -3422,6 +3460,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; + getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -3492,6 +3532,10 @@ declare namespace ts { /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; } + interface ApplicableRefactorInfo { + name: string; + description: string; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -4006,6 +4050,7 @@ declare namespace ts { reportDiagnostics?: boolean; moduleName?: string; renamedDependencies?: MapLike; + transformers?: CustomTransformers; } interface TranspileOutput { outputText: string; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 4fe0eb9bf25..9f28644b4e5 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -365,10 +365,11 @@ var ts; // Transformation nodes SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -512,6 +513,13 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + /* @internal */ + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); /** Return code used by getEmitOutput function to indicate status of the function */ var ExitStatus; (function (ExitStatus) { @@ -527,12 +535,23 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + // Options + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + // Error handling + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + // State + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { @@ -677,6 +696,12 @@ var ts; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); /* @internal */ + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type) + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + /* @internal */ var CheckFlags; (function (CheckFlags) { CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; @@ -751,7 +776,7 @@ var ts; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; @@ -761,7 +786,7 @@ var ts; /* @internal */ TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; @@ -770,7 +795,7 @@ var ts; TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 17810431] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; @@ -1119,6 +1144,7 @@ var ts; EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1138,17 +1164,22 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; // Helpers included by ES2017 for..await..of - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; // Helpers included by ES2015 spread ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1450,12 +1481,6 @@ var ts; return undefined; } ts.forEach = forEach; - /** - * Iterates through the parent chain of a node and performs the callback on each parent until the callback - * returns a truthy value, then returns that value. - * If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit" - * At that point findAncestor returns undefined. - */ function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1477,6 +1502,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; /** * Iterates through `array` by index and performs the callback on each element of array until the callback * returns a falsey value, then returns false. @@ -1704,6 +1738,35 @@ var ts; return result; } ts.flatMap = flatMap; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * Avoids allocation if all elements map to themselves. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -2881,6 +2944,11 @@ var ts; } ts.startsWith = startsWith; /* @internal */ + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + /* @internal */ function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -4058,6 +4126,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -4165,7 +4234,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -4360,6 +4429,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4655,6 +4732,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -4700,6 +4778,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4781,6 +4861,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -5443,9 +5526,10 @@ var ts; ts.getTrailingCommentRanges = getTrailingCommentRanges; /** Optionally, get the shebang */ function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -6654,9 +6738,7 @@ var ts; ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; /* @internal */ function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -6849,28 +6931,30 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, - // or an escaped quoted form of the original text if it's string-like. + // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { case 9 /* StringLiteral */: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13 /* NoSubstitutionTemplateLiteral */: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14 /* TemplateHead */: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15 /* TemplateMiddle */: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16 /* TemplateTail */: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8 /* NumericLiteral */: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier; @@ -7099,10 +7183,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 /* EnumDeclaration */ && isConst(node); } @@ -7382,6 +7462,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151 /* MethodDeclaration */: @@ -7638,6 +7727,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 /* CallExpression */ || node.kind === 182 /* NewExpression */; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183 /* TaggedTemplateExpression */) { return node.tag; @@ -8230,21 +8323,46 @@ var ts; ts.isInAmbientContext = isInAmbientContext; // True if the given identifier, string literal, or number literal is the name of a declaration node function isDeclarationName(name) { - if (name.kind !== 71 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) { - return false; + switch (name.kind) { + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 /* ImportSpecifier */ || parent.kind === 246 /* ExportSpecifier */) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194 /* BinaryExpression */) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0 /* None */: + case 2 /* ModuleExports */: + return undefined; + case 1 /* ExportsProperty */: + if (lhs.kind === 71 /* Identifier */) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4 /* ThisProperty */: + case 5 /* Property */: + return lhs.name; + case 3 /* PrototypeProperty */: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 144 /* ComputedPropertyName */ && @@ -8357,21 +8475,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -8399,12 +8515,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } var flags = 0 /* Normal */; switch (node.kind) { case 228 /* FunctionDeclaration */: @@ -8457,7 +8574,8 @@ var ts; * Symbol. */ function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -8740,6 +8858,8 @@ var ts; return 2; case 198 /* SpreadElement */: return 1; + case 297 /* CommaListExpression */: + return 0; default: return -1; } @@ -8853,14 +8973,15 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); // Replace non-ASCII characters with '\uNNNN' escapes if any exist. // Otherwise just return the original string. return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -8949,7 +9070,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -9015,7 +9136,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; /** @@ -9579,13 +9700,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0 /* CarriageReturnLineFeed */) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0 /* CarriageReturnLineFeed */: + return carriageReturnLineFeed; + case 1 /* LineFeed */: + return lineFeed; } - else if (options.newLine === 1 /* LineFeed */) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -9913,10 +10034,6 @@ var ts; return node.kind === 71 /* Identifier */; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190 /* VoidExpression */; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return isIdentifier(node) && node.autoGenerateKind > 0 /* None */; @@ -9989,9 +10106,20 @@ var ts; || kind === 153 /* GetAccessor */ || kind === 154 /* SetAccessor */ || kind === 157 /* IndexSignature */ - || kind === 206 /* SemicolonClassElement */; + || kind === 206 /* SemicolonClassElement */ + || kind === 247 /* MissingDeclaration */; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 /* ConstructSignature */ + || kind === 155 /* CallSignature */ + || kind === 148 /* PropertySignature */ + || kind === 150 /* MethodSignature */ + || kind === 157 /* IndexSignature */ + || kind === 247 /* MissingDeclaration */; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 /* PropertyAssignment */ @@ -10209,6 +10337,7 @@ var ts; || kind === 198 /* SpreadElement */ || kind === 202 /* AsExpression */ || kind === 200 /* OmittedExpression */ + || kind === 297 /* CommaListExpression */ || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -10297,6 +10426,10 @@ var ts; return node.kind === 237 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238 /* ImportDeclaration */; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239 /* ImportClause */; } @@ -10319,6 +10452,10 @@ var ts; return node.kind === 246 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243 /* ExportAssignment */; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 /* ModuleDeclaration */ || node.kind === 232 /* EnumDeclaration */; } @@ -10390,8 +10527,8 @@ var ts; || kind === 213 /* WhileStatement */ || kind === 220 /* WithStatement */ || kind === 295 /* NotEmittedStatement */ - || kind === 298 /* EndOfDeclarationMarker */ - || kind === 297 /* MergeDeclarationMarker */; + || kind === 299 /* EndOfDeclarationMarker */ + || kind === 298 /* MergeDeclarationMarker */; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -10517,6 +10654,49 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 6 /* Synthetic */) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + // shift current back to previous, and then reuse previous' array + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -10983,16 +11163,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - // Identifiers - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71 /* Identifier */); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; node.autoGenerateKind = 0 /* None */; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable) { @@ -11087,240 +11275,13 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - // Type Elements - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - // Types - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169 /* ThisType */); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173 /* LiteralType */); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159 /* TypeReference */); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158 /* TypePredicate */); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162 /* TypeQuery */); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164 /* ArrayType */); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168 /* ParenthesizedType */); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163 /* TypeLiteral */); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165 /* TupleType */); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172 /* MappedType */); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170 /* TypeOperator */); - typeOperatorNode.operator = 127 /* KeyOfKeyword */; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171 /* IndexedAccessType */); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; - // Type Declarations + // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145 /* TypeParameter */); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145 /* TypeParameter */); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -11331,44 +11292,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - // Signature elements - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148 /* PropertySignature */); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157 /* IndexSignature */); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; - // Signature elements function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146 /* Parameter */); node.decorators = asNodeArray(decorators); @@ -11405,7 +11328,27 @@ var ts; : node; } ts.updateDecorator = updateDecorator; - // Type members + // Type Elements + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148 /* PropertySignature */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); @@ -11427,7 +11370,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -11440,7 +11400,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -11450,7 +11410,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -11518,6 +11478,251 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157 /* IndexSignature */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + /* @internal */ + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + // Types + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158 /* TypePredicate */); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159 /* TypeReference */); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162 /* TypeQuery */); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163 /* TypeLiteral */); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164 /* ArrayType */); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165 /* TupleType */); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166 /* UnionType */, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167 /* IntersectionType */, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168 /* ParenthesizedType */); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169 /* ThisType */); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170 /* TypeOperator */); + node.operator = 127 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171 /* IndexedAccessType */); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172 /* MappedType */); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173 /* LiteralType */); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174 /* ObjectBindingPattern */); @@ -11565,9 +11770,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -11580,9 +11784,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -11632,9 +11835,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -11824,10 +12027,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -11954,6 +12157,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204 /* MetaProperty */); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205 /* TemplateSpan */); @@ -11969,6 +12185,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206 /* SemicolonClassElement */); + } + ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { var block = createSynthesizedNode(207 /* Block */); @@ -11979,7 +12199,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -11999,35 +12219,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227 /* VariableDeclarationList */); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226 /* VariableDeclaration */); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209 /* EmptyStatement */); } @@ -12246,6 +12437,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225 /* DebuggerStatement */); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226 /* VariableDeclaration */); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227 /* VariableDeclarationList */); + node.flags |= flags & 3 /* BlockScoped */; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); @@ -12294,6 +12518,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230 /* InterfaceDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231 /* TypeAliasDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); @@ -12314,7 +12580,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233 /* ModuleDeclaration */); - node.flags |= flags; + node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -12355,6 +12621,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236 /* NamespaceExportDeclaration */); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); @@ -12385,7 +12663,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -12573,19 +12852,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254 /* JsxAttributes */); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253 /* JsxAttribute */); node.name = name; @@ -12600,6 +12866,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254 /* JsxAttributes */); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255 /* JsxSpreadAttribute */); node.expression = expression; @@ -12626,20 +12904,6 @@ var ts; } ts.updateJsxExpression = updateJsxExpression; // Clauses - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259 /* HeritageClause */); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); @@ -12648,10 +12912,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -12661,12 +12925,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259 /* HeritageClause */); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260 /* CatchClause */); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -12675,10 +12951,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; // Property assignments @@ -12691,10 +12967,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -12705,10 +12981,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -12718,10 +12994,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; // Enum @@ -12833,7 +13108,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -12845,7 +13120,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(298 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -12874,6 +13149,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297 /* CommaListExpression */) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297 /* CommaListExpression */); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266 /* Bundle */); node.sourceFiles = sourceFiles; @@ -13250,7 +13548,25 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - // Compound nodes + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -13512,7 +13828,11 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -13686,9 +14006,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) @@ -13846,16 +14167,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195 /* ConditionalExpression */, 55 /* QuestionToken */); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -14131,6 +14442,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166 /* UnionType */: + case 167 /* IntersectionType */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; /** * Clones a series of not-emitted expressions with a new inner expression. * @@ -14311,7 +14650,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -15079,6 +15418,8 @@ var ts; return visitNode(cbNode, node.expression); case 247 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); + case 297 /* CommaListExpression */: + return visitNodes(cbNodes, node.elements); case 249 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -20465,6 +20806,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -21452,7 +21795,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -21480,7 +21823,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { // bind in strict mode source files with alwaysStrict option return true; } @@ -21517,12 +21860,13 @@ 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.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; @@ -21530,7 +21874,7 @@ var ts; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152 /* Constructor */: @@ -21674,9 +22018,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } @@ -23592,7 +23936,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) checkStrictModeEvalOrArguments(node, node.name); @@ -23611,7 +23955,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -23626,7 +23970,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -23639,7 +23983,7 @@ var ts; return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -24526,13 +24870,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - /** Adds `isExernalLibraryImport` to a Resolved to get a ResolvedModule. */ - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -24860,6 +25202,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -25062,13 +25406,24 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, /*jsOnly*/ false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ /* @internal */ - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -25099,7 +25454,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -25462,6 +25816,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -25613,13 +25968,16 @@ var ts; // since we are only interested in declarations of the module itself return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -25702,11 +26060,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32 /* StringLiteral */, ""); - var zeroType = getLiteralTypeForText(64 /* NumberLiteral */, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -25972,16 +26332,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -26063,9 +26423,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 /* Object */ ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } @@ -26073,7 +26430,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -26109,7 +26466,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { // nodes are in different files and order cannot be determined return true; } @@ -26205,7 +26563,11 @@ var ts; // Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and // the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with // the given name can be found. - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; var propertyWithInvalidInitializer; @@ -26215,7 +26577,7 @@ var ts; loop: while (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { // symbol lookup restrictions for function-like declarations @@ -26286,12 +26648,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { + if (result = lookup(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { break loop; } break; case 232 /* EnumDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; @@ -26306,7 +26668,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 107455 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -26316,7 +26678,7 @@ var ts; case 229 /* ClassDeclaration */: case 199 /* ClassExpression */: case 230 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -26351,7 +26713,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -26412,7 +26774,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -26422,7 +26784,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -26541,6 +26913,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -26573,13 +26949,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2 /* BlockScopedVariable */) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32 /* Class */) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384 /* Enum */) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256 /* RegularEnum */) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -26595,7 +26971,7 @@ var ts; if (node.kind === 237 /* ImportEqualsDeclaration */) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238 /* ImportDeclaration */; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -26719,10 +27095,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); @@ -26738,7 +27114,7 @@ var ts; case 242 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 243 /* ExportAssignment */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236 /* NamespaceExportDeclaration */: @@ -26887,7 +27263,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -26909,6 +27285,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, /*withAugmentations*/ true); if (ambientModule) { return ambientModule; @@ -26978,7 +27359,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -27128,7 +27508,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32 /* StringLiteral */, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } // A reserved member name starts with two underscores, but the third character cannot be an underscore // or the @ symbol. A third underscore indicates an escaped form of an identifer that started @@ -27458,34 +27838,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 /* NoTruncation */ ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4 /* NoTruncation */) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128 /* UseFullyQualifiedType */) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048 /* SuppressAnyReturnType */) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1 /* WriteArrayAsGenericType */) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32 /* WriteTypeArgumentsOfSignature */) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -27495,15 +27900,14 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; - // TODO(aozgaa): should we return implict any (undefined) or explicit any (keywordtypenode)? return undefined; } if (type.flags & 1 /* Any */) { @@ -27518,23 +27922,25 @@ var ts; if (type.flags & 8 /* Boolean */) { return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } - if (type.flags & 16 /* Enum */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + } + if (type.flags & 272 /* EnumLike */) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (32 /* StringLiteral */)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } if (type.flags & (64 /* NumberLiteral */)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128 /* BooleanLiteral */) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256 /* EnumLiteral */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); - } if (type.flags & 1024 /* Void */) { return ts.createKeywordTypeNode(105 /* VoidKeyword */); } @@ -27554,8 +27960,8 @@ var ts; return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -27566,39 +27972,31 @@ var ts; ts.Debug.assert(!!(type.flags & 32768 /* Object */)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3 /* ClassOrInterface */) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - // TODO(aozgaa): handle type arguments. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); - } - if (type.flags & 16384 /* TypeParameter */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & 16384 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536 /* Union */) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166 /* UnionType */, unionTypeNodes); + if (type.flags & (65536 /* Union */ | 131072 /* Intersection */)) { + var types = type.flags & 65536 /* Union */ ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 /* Union */ ? 166 /* UnionType */ : 167 /* IntersectionType */, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072 /* Intersection */) { - return ts.createUnionOrIntersectionTypeNode(167 /* IntersectionType */, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { ts.Debug.assert(!!(type.flags & 32768 /* Object */)); // The type is an object literal type. @@ -27606,35 +28004,23 @@ var ts; } if (type.flags & 262144 /* Index */) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288 /* IndexedAccess */) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -27643,14 +28029,14 @@ var ts; if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); } else if (ts.contains(context.symbolStack, symbol)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - var entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false); + var entityName = symbolToName(typeAlias, context, 793064 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -27696,41 +28082,53 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(/*members*/ undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, /*expectsIdentifier*/ false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + // Unnamed function expressions and arrow functions have reserved names that we don't want to display + var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8 /* Tuple */) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -27738,7 +28136,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -27751,48 +28149,72 @@ var ts; // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - var qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, /*right*/ undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); + qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71 /* Identifier */) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71 /* Identifier */) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); } var properties = resolvedType.properties; if (!properties) { @@ -27801,86 +28223,131 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - // TODO(aozgaa): should we create a node with explicit or implict any? - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119 /* AnyKeyword */); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 136 /* StringKeyword */ : 133 /* NumberKeyword */); - var name = ts.getNameFromIndexInfo(indexInfo); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration( + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 /* Identifier */ ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 /* AnyKeyword */ ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, /*expectsIdentifier*/ true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146 /* Parameter */); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration.name.kind === 71 /* Identifier */ ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - // TODO(aozgaa): In the future, check initializer accessibility. - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24 /* DotDotDotToken */), - // Clone name to remove trivia. - ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55 /* QuestionToken */), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048 /* Undefined */); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter( + /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + /*initializer*/ undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176 /* BindingElement */) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0 /* None */, /*endOfChain*/ true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -27888,19 +28355,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); - // const parentIndex = index - 1; var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -27909,20 +28375,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ @@ -27954,28 +28410,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199 /* ClassExpression */: - return "(Anonymous class)"; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199 /* ClassExpression */: + return "(Anonymous class)"; + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -27993,12 +28450,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144 /* Nullable */)) { if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { - var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536 /* Union */) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -28034,13 +28493,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -28097,7 +28557,7 @@ var ts; if (parentSymbol) { // Write type arguments of instantiated class/interface here if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -28180,12 +28640,17 @@ var ts; else if (getObjectFlags(type) & 4 /* Reference */) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256 /* EnumLiteral */) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - writePunctuation(writer, 23 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); + // In a literal enum type with a single member E { A }, E and E.A denote the + // same type. We always display this type simply as E. + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23 /* DotToken */); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (16 /* Enum */ | 16384 /* TypeParameter */)) { + else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 16384 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } @@ -28541,7 +29006,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048 /* Undefined */); + type = getNullableType(type, 2048 /* Undefined */); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -28808,10 +29273,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246 /* ExportSpecifier */) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } var result = []; if (exportSymbol) { @@ -28954,7 +29416,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -29070,7 +29532,7 @@ var ts; return expr.kind === 177 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + return strictNullChecks && optional ? getNullableType(type, 2048 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { @@ -29173,6 +29635,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 /* BinaryExpression */ ? declaration : @@ -29189,17 +29652,25 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536 /* JavaScriptFile */) { - // If there is a JSDoc type, use it - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + // If there is a JSDoc type, use it + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + // If we don't have an explicit JSDoc type, get the type from the expression. + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, /*subtypeReduction*/ true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, /*subtypeReduction*/ true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding @@ -29449,7 +29920,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? getNullableType(type, 2048 /* Undefined */) : type; } } } @@ -29512,7 +29983,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -29711,6 +30182,7 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && @@ -29718,7 +30190,7 @@ var ts; // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the // class and all return the instance type of the class. There is no need for further checks and we can apply the // type arguments in the same manner as a type reference to get the same error reporting experience. - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; @@ -29902,77 +30374,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 /* NumericLiteral */ || + return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || expr.kind === 192 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */ || - expr.kind === 71 /* Identifier */ && !!symbol.exports.get(expr.text); + expr.kind === 71 /* Identifier */ && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256 /* EnumLiteral */); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16 /* Enum */); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232 /* EnumDeclaration */) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1 /* Literal */) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536 /* Union */; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); + if (enumType_1.flags & 65536 /* Union */) { + enumType_1.flags |= 256 /* EnumLiteral */; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16 /* Enum */); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 /* Union */ ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -30219,7 +30694,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -30306,8 +30781,8 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type = types_2[_i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -30481,7 +30956,7 @@ var ts; // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (t.flags & 32 /* StringLiteral */) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864 /* Optional */); var prop = createSymbol(4 /* Property */ | (isOptional ? 67108864 /* Optional */ : 0), propName); @@ -30613,6 +31088,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536 /* Union */) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190 /* Primitive */) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : type.flags & 524288 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : @@ -30674,8 +31170,8 @@ var ts; if (t.flags & 196608 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -30731,7 +31227,7 @@ var ts; var t = type.flags & 540672 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 /* StringLike */ ? globalStringType : - t.flags & 340 /* NumberLike */ ? globalNumberType : + t.flags & 84 /* NumberLike */ ? globalNumberType : t.flags & 136 /* BooleanLike */ ? globalBooleanType : t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : @@ -30746,12 +31242,12 @@ var ts; var commonFlags = isUnion ? 0 /* None */ : 67108864 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -30823,7 +31319,7 @@ var ts; function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); // We need to filter out partial properties in union types - return property && !(getCheckFlags(property) & 16 /* Partial */) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined; } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when @@ -31231,8 +31727,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -31367,8 +31864,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -31399,7 +31896,7 @@ var ts; return ts.length(type.target.typeParameters); } // Get type from reference to class or interface - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -31414,7 +31911,7 @@ var ts; // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -31437,7 +31934,7 @@ var ts; // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the // declared type. Instantiations are cached using the type identities of the type arguments as the key. - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -31449,7 +31946,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -31489,14 +31985,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064 /* Type */) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288 /* TypeAlias */) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 /* Value */ && node.kind === 277 /* JSDocTypeReference */) { // A JSDocTypeReference may have resolved to a value (as opposed to a type). In @@ -31559,10 +32056,7 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064 /* Type */) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the // type reference in checkTypeReferenceOrExpressionWithTypeArguments. @@ -31571,6 +32065,9 @@ var ts; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -31812,14 +32309,14 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -31827,8 +32324,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -31959,8 +32456,8 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -32024,9 +32521,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32 /* StringLiteral */, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -32056,12 +32553,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */ | 256 /* EnumLiteral */) ? - indexType.text : + var propName = indexType.flags & 96 /* StringOrNumberLiteral */ ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -32076,11 +32573,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { @@ -32105,7 +32602,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 /* String */ | 4 /* Number */)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -32258,7 +32755,7 @@ var ts; var rightProp = _a[_i]; // we approximate own properties as non-methods plus methods that are inside the object literal var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -32275,11 +32772,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 67108864 /* Optional */) { + if (rightProp.flags & 67108864 /* Optional */) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 67108864 /* Optional */); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -32306,15 +32803,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 1048576 /* FreshLiteral */)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.text); + var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -32325,11 +32823,17 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 /* StringLiteral */ ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 /* NumberLiteral */ : 32 /* StringLiteral */) | (enumId ? 256 /* EnumLiteral */ : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -32593,7 +33097,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { var links = getSymbolLinks(symbol); // If symbol being instantiated is itself a instantiation, fetch the original target and combine the // type mappers. This ensures that original type identities are properly preserved and that aliases @@ -33087,29 +33591,27 @@ var ts; type.flags & 131072 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */) || - (source.flags & 65536 /* Union */) !== (target.flags & 65536 /* Union */)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8 /* EnumMember */) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -33120,42 +33622,50 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192 /* Never */) + var s = source.flags; + var t = target.flags; + if (t & 8192 /* Never */) return false; - if (target.flags & 1 /* Any */ || source.flags & 8192 /* Never */) + if (t & 1 /* Any */ || s & 8192 /* Never */) return true; - if (source.flags & 262178 /* StringLike */ && target.flags & 2 /* String */) + if (s & 262178 /* StringLike */ && t & 2 /* String */) return true; - if (source.flags & 340 /* NumberLike */ && target.flags & 4 /* Number */) + if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && + t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) return true; - if (source.flags & 136 /* BooleanLike */ && target.flags & 8 /* Boolean */) + if (s & 84 /* NumberLike */ && t & 4 /* Number */) return true; - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) + if (s & 64 /* NumberLiteral */ && s & 256 /* EnumLiteral */ && + t & 64 /* NumberLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) return true; - if (source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */ && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) return true; - if (source.flags & 2048 /* Undefined */ && (!strictNullChecks || target.flags & (2048 /* Undefined */ | 1024 /* Void */))) + if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 /* Null */ && (!strictNullChecks || target.flags & 4096 /* Null */)) + if (s & 256 /* EnumLiteral */ && t & 256 /* EnumLiteral */) { + if (s & 65536 /* Union */ && t & 65536 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 /* Literal */ && t & 224 /* Literal */ && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 /* Undefined */ && (!strictNullChecks || t & (2048 /* Undefined */ | 1024 /* Void */))) return true; - if (source.flags & 32768 /* Object */ && target.flags & 16777216 /* NonPrimitive */) + if (s & 4096 /* Null */ && (!strictNullChecks || t & 4096 /* Null */)) + return true; + if (s & 32768 /* Object */ && t & 16777216 /* NonPrimitive */) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1 /* Any */) + if (s & 1 /* Any */) return true; - if ((source.flags & 4 /* Number */ | source.flags & 64 /* NumberLiteral */) && target.flags & 272 /* EnumLike */) + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (s & (4 /* Number */ | 64 /* NumberLiteral */) && !(s & 256 /* EnumLiteral */) && (t & 16 /* Enum */ || t & 64 /* NumberLiteral */ && t & 256 /* EnumLiteral */)) return true; - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 256 /* EnumLiteral */ && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 16 /* Enum */ && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -33378,29 +33888,6 @@ var ts; } return 0 /* False */; } - // Check if a property with the given name is known anywhere in the given type. In an object type, a property - // is considered known if the object type is empty and the check is for assignability, if the object type has - // index signatures, or if the property is actually declared in the object type. In a union or intersection - // type, a property is considered known if it is known in any constituent type. - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. - return true; - } - } - else if (type.flags & 196608 /* UnionOrIntersection */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); @@ -33789,10 +34276,10 @@ var ts; } } else if (!(targetProp.flags & 16777216 /* Prototype */)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - if (getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -33901,24 +34388,38 @@ var ts; } var result = -1 /* True */; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - // Only elaborate errors from the first failure - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 /* Instantiated */ && getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We instantiations of the same anonymous type (which typically will be the type of a method). + // Simply do a pairwise comparison of the signatures in the two signature lists instead of the + // much more expensive N * M comparison matrix we explore below. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0 /* False */; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; } - return 0 /* False */; } return result; } @@ -34038,7 +34539,7 @@ var ts; // Invoke the callback for each underlying property symbol of the given symbol and return the first // value that isn't undefined. function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6 /* Synthetic */) { + if (ts.getCheckFlags(prop) & 6 /* Synthetic */) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -34065,13 +34566,13 @@ var ts; } // Return true if source property is a valid override of protected parts of target property. function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is the constructor type for an abstract class @@ -34120,8 +34621,8 @@ var ts; if (sourceProp === targetProp) { return -1 /* True */; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -34215,8 +34716,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -34224,8 +34725,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -34251,7 +34752,7 @@ var ts; return getUnionType(types, /*subtypeReduction*/ true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { // The downfallType/bestSupertypeDownfallType is the first type that caused a particular candidate @@ -34299,27 +34800,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; + return (type.flags & (224 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; } function isLiteralType(type) { return type.flags & 8 /* Boolean */ ? true : - type.flags & 65536 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 /* Union */ ? type.flags & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 /* StringLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } /** @@ -34331,8 +34832,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; @@ -34342,35 +34843,35 @@ var ts; // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { return type.flags & 65536 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 /* StringLiteral */ ? type.text === "" ? 32 /* StringLiteral */ : 0 : - type.flags & 64 /* NumberLiteral */ ? type.text === "0" ? 64 /* NumberLiteral */ : 0 : + type.flags & 32 /* StringLiteral */ ? type.value === "" ? 32 /* StringLiteral */ : 0 : + type.flags & 64 /* NumberLiteral */ ? type.value === 0 ? 64 /* NumberLiteral */ : 0 : type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : type.flags & 7406 /* PossiblyFalsy */; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178 /* StringLike */) - types.push(emptyStringType); - if (flags & 340 /* NumberLike */) - types.push(zeroType); - if (flags & 136 /* BooleanLike */) - types.push(falseType); - if (flags & 1024 /* Void */) - types.push(voidType); - if (flags & 2048 /* Undefined */) - types.push(undefinedType); - if (flags & 4096 /* Null */) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392 /* DefinitelyFalsy */); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 /* String */ ? emptyStringType : + type.flags & 4 /* Number */ ? zeroType : + type.flags & 8 /* Boolean */ || type === falseType ? falseType : + type.flags & (1024 /* Void */ | 2048 /* Undefined */ | 4096 /* Null */) || + type.flags & 32 /* StringLiteral */ && type.value === "" || + type.flags & 64 /* NumberLiteral */ && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 /* Undefined */ | 4096 /* Null */); + return missing === 0 ? type : + missing === 2048 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 4096 /* Null */ ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; } @@ -34537,7 +35038,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { @@ -34622,7 +35123,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864 /* Optional */; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -34655,20 +35156,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -34683,7 +35174,7 @@ var ts; } return; } - if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || + if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 256 /* EnumLiteral */ && target.flags & 256 /* EnumLiteral */) || source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. @@ -34800,26 +35291,29 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768 /* Object */) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + var isNonConstructorObject = target.flags & 32768 /* Object */ && + !(getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -34908,8 +35402,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -35005,7 +35499,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -35018,11 +35512,13 @@ var ts; // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { if (node.kind === 71 /* Identifier */) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99 /* ThisKeyword */) { return "0"; @@ -35091,7 +35587,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); } @@ -35154,8 +35650,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -35173,15 +35669,16 @@ var ts; return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; } if (flags & 32 /* StringLiteral */) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : - type.text === "" ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; + isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : + isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; } if (flags & (4 /* Number */ | 16 /* Enum */)) { return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; } - if (flags & (64 /* NumberLiteral */ | 256 /* EnumLiteral */)) { - var isZero = type.text === "0"; + if (flags & 64 /* NumberLiteral */) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; @@ -35388,7 +35885,7 @@ var ts; } return true; } - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) { + if (source.flags & 256 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -35414,8 +35911,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -35495,8 +35992,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192 /* Never */)) { if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -35527,7 +36024,7 @@ var ts; parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 /* NumberLike */ | 2048 /* Undefined */); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */ | 2048 /* Undefined */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -35553,7 +36050,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -35695,7 +36192,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | 2048 /* Undefined */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */ | 2048 /* Undefined */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -36202,6 +36699,26 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048 /* Undefined */); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 /* PropertyAccessExpression */ || + parent.kind === 181 /* CallExpression */ && parent.expression === node || + parent.kind === 180 /* ElementAccessExpression */ && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144 /* Nullable */); + } + function getDeclaredOrApparentType(symbol, node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -36268,7 +36785,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -36309,7 +36826,7 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048 /* Undefined */); + getNullableType(type, 2048 /* Undefined */); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the @@ -36317,7 +36834,7 @@ var ts; if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -37214,8 +37731,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -37329,7 +37846,7 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340 /* NumberLike */); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84 /* NumberLike */); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -37367,7 +37884,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -37518,6 +38035,8 @@ var ts; 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; } return spread; @@ -37596,6 +38115,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -37613,6 +38136,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); @@ -37622,39 +38148,39 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } // Handle children attribute var parent = openingLikeElement.parent.kind === 249 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that // because then type of children property will have constituent of string type. if (child.kind === 10 /* JsxText */) { @@ -37666,11 +38192,11 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - // Error if there is a attribute named "children" and children element. - // This is because children element will overwrite the value from attributes - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } // If there are children in the body of JSX element, create dummy attribute "children" with anyType so that it will pass the attribute checking process @@ -37681,7 +38207,12 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable @@ -37689,8 +38220,7 @@ var ts; */ function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; - result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag; + result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */; return result; } @@ -37768,7 +38298,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -37820,6 +38361,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072 /* Intersection */) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } /** * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. * Return only attributes type of successfully resolved call signature. @@ -37840,6 +38395,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); @@ -37878,6 +38434,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -37947,7 +38504,7 @@ var ts; // Hello World var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -38152,6 +38709,34 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if the object type is empty and the check is for assignability, if the object type has + * index signatures, or if the property is actually declared in the object type. In a union or intersection + * type, a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & 196608 /* UnionOrIntersection */) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } /** * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" @@ -38180,7 +38765,20 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -38200,29 +38798,11 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149 /* PropertyDeclaration */; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; - } - if (getCheckFlags(s) & 6 /* Synthetic */) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : - checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : - 16 /* Protected */; - var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216 /* Prototype */) { - return 4 /* Public */ | 32 /* Static */; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 /* Method */ || getCheckFlags(symbol) & 4 /* SyntheticMethod */); + return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); } /** * Check whether the requested property access is valid. @@ -38233,11 +38813,11 @@ var ts; * @param prop The symbol for the right hand side of the property access. */ function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 /* PropertyAccessExpression */ || node.kind === 226 /* VariableDeclaration */ ? node.name : node.right; - if (getCheckFlags(prop) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; @@ -38335,42 +38915,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { - if (getCheckFlags(prop) & 1 /* Instantiated */) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -38407,7 +38951,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -38426,6 +38970,126 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455 /* Value */); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 0.3 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + * Names longer than 30 characters don't get suggestions because Levenshtein distance is an n**2 algorithm. + */ + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500 /* ClassMember */) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { + if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 /* PropertyAccessExpression */ ? node.expression @@ -38548,7 +39212,16 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183 /* TaggedTemplateExpression */) { checkExpression(node.template); } @@ -38579,8 +39252,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -38688,7 +39361,7 @@ var ts; // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } // Too many arguments implies incorrect arity. if (!signature.hasRestParameter && argCount > signature.parameters.length) { @@ -39059,7 +39732,7 @@ var ts; case 71 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getLiteralTypeForText(32 /* StringLiteral */, element.name.text); + return getLiteralType(element.name.text); case 144 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { @@ -39169,7 +39842,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183 /* TaggedTemplateExpression */; var isDecorator = node.kind === 147 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -39199,7 +39872,7 @@ var ts; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -39300,7 +39973,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -39308,14 +39981,45 @@ var ts; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information that anySignature. @@ -39323,8 +40027,8 @@ var ts; // declare function f(a: { xa: number; xb: number; }); // f({ | if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -39334,14 +40038,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -39509,7 +40205,7 @@ var ts; // only the class declaration node will have the Abstract flag set. var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128 /* Abstract */) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } // TS 1.0 spec: 4.11 @@ -39676,8 +40372,8 @@ var ts; if (elementType.flags & 65536 /* Union */) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -39854,7 +40550,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048 /* Undefined */); + return getNullableType(type, 2048 /* Undefined */); } } return type; @@ -39920,11 +40616,11 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 /* ObjectBindingPattern */ || - parameter.valueDeclaration.name.kind === 175 /* ArrayBindingPattern */)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -40055,7 +40751,7 @@ var ts; // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. - return (functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + return (functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? createPromiseReturnType(func, widenedType) // Async function : widenedType; // Generator function, AsyncGenerator function, or normal function } @@ -40251,7 +40947,7 @@ var ts; ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = node.type && - ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ ? + ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function if ((functionFlags & 1 /* Generator */) === 0) { @@ -40278,7 +40974,7 @@ var ts; // its return type annotation. var exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } @@ -40291,7 +40987,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -40304,8 +41000,8 @@ var ts; // Get accessors without matching set accessors // Enum members // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) - return !!(getCheckFlags(symbol) & 8 /* Readonly */ || - symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || + symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || symbol.flags & 8 /* EnumMember */); @@ -40392,7 +41088,7 @@ var ts; return silentNeverType; } if (node.operator === 38 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37 /* PlusToken */: @@ -40439,8 +41135,8 @@ var ts; } if (type.flags & 196608 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -40457,8 +41153,8 @@ var ts; } if (type.flags & 65536 /* Union */) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -40467,8 +41163,8 @@ var ts; } if (type.flags & 131072 /* Intersection */) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -40513,7 +41209,7 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 /* NumberLike */ | 512 /* ESSymbol */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 /* NumberLike */ | 512 /* ESSymbol */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) { @@ -40808,7 +41504,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340 /* NumberLike */) && isTypeOfKind(rightType, 340 /* NumberLike */)) { + if (isTypeOfKind(leftType, 84 /* NumberLike */) && isTypeOfKind(rightType, 84 /* NumberLike */)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; @@ -40868,7 +41564,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53 /* AmpersandAmpersandToken */: return getTypeFacts(leftType) & 1048576 /* Truthy */ ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54 /* BarBarToken */: return getTypeFacts(leftType) & 2097152 /* Falsy */ ? @@ -40961,12 +41657,15 @@ var ts; // we are in a yield context. var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2 /* Async */) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 4096 /* AsyncDelegator */); - } + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256 /* Values */); } } @@ -41012,9 +41711,9 @@ var ts; } switch (node.kind) { case 9 /* StringLiteral */: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32 /* StringLiteral */, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101 /* TrueKeyword */: return trueType; case 86 /* FalseKeyword */: @@ -41079,7 +41778,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 /* Literal */ | 262144 /* Index */)); + return maybeTypeOfKind(contextualType, (224 /* Literal */ | 262144 /* Index */)); } return false; } @@ -41424,17 +42123,18 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7 /* InvalidAsyncOrAsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 64 /* Awaiter */); - if (languageVersion < 2 /* ES2015 */) { - checkExternalEmitHelpers(node, 128 /* Generator */); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } - } - if ((functionFlags & 5 /* InvalidGenerator */) === 1 /* Generator */) { - if (functionFlags & 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 2048 /* AsyncGenerator */); + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); } - else if (languageVersion < 2 /* ES2015 */) { + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, 128 /* Generator */); } } @@ -41457,7 +42157,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5 /* InvalidGenerator */) === 1 /* Generator */) { + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -41476,7 +42176,7 @@ var ts; checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } - else if ((functionFlags_1 & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { checkAsyncFunctionReturnType(node); } } @@ -41595,7 +42295,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -41683,7 +42383,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -41840,7 +42541,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 /* Enum */ && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + if (type.flags & 16 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -41883,7 +42584,7 @@ var ts; } // Check if we're indexing with a numeric type and the object type is a generic // type with a constraint that has a numeric index signature. - if (maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && isTypeOfKind(indexType, 340 /* NumberLike */)) { + if (maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && isTypeOfKind(indexType, 84 /* NumberLike */)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1 /* Number */)) { return type; @@ -41943,16 +42644,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1 /* Export */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2 /* Ambient */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 /* Private */ | 16 /* Protected */)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128 /* Abstract */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -41963,7 +42664,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -42087,7 +42788,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -42101,8 +42802,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -42160,12 +42861,13 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -42480,7 +43182,9 @@ var ts; * marked as referenced to prevent import elision. */ function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (rootSymbol @@ -42490,6 +43194,57 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167 /* IntersectionType */: + case 166 /* UnionType */: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168 /* ParenthesizedType */: + return getEntityNameForDecoratorMetadata(node.type); + case 159 /* TypeReference */: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -42520,7 +43275,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -42529,15 +43284,15 @@ var ts; case 154 /* SetAccessor */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149 /* PropertyDeclaration */: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146 /* Parameter */: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -42671,15 +43426,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146 /* Parameter */) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -42759,7 +43515,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -42827,7 +43583,7 @@ var ts; if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { var isDeclaration_1 = node.kind !== 71 /* Identifier */; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -42841,7 +43597,7 @@ var ts; if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { var isDeclaration_2 = node.kind !== 71 /* Identifier */; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -43107,7 +43863,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -43222,11 +43978,14 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216 /* ForOfStatement */) { if (node.awaitModifier) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 8192 /* ForAwaitOfIncludes */); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 5 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); } } @@ -43609,7 +44368,7 @@ var ts; return !!(node.kind === 153 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */))); } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); @@ -43831,13 +44590,16 @@ var ts; } var propDeclaration = prop.valueDeclaration; // index is numeric and property name is not valid numeric literal - if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } // perform property check if property or indexer is declared in 'type' - // this allows to rule out cases when both property and indexer are inherited from the base class + // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 /* BinaryExpression */ || + ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -44076,7 +44838,7 @@ var ts; function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags - return getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; + return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -44109,7 +44871,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { // In order to resolve whether the inherited method was overridden in the base class or not, @@ -44132,15 +44894,11 @@ var ts; } else { // derived overrides base. - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) { // either base or derived property is private - not override, skip it continue; } - if ((baseDeclarationFlags & 32 /* Static */) !== (derivedDeclarationFlags & 32 /* Static */)) { - // value of 'static' is not the same for properties - not override, skip it - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; @@ -44160,7 +44918,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -44247,97 +45005,88 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); - var autoValue = 0; // set to undefined when enum member is non-constant - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); + nodeLinks.flags |= 16384 /* EnumValuesComputed */; + var autoValue = 0; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - // In ambient enum declarations that specify no const modifier, enum member declarations - // that omit a value are considered computed members (as opposed to having auto-incremented values assigned). - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - // If the member declaration specifies no value, the member is considered a constant enum member. - // If the member is the first member in the enum declaration, it is assigned the value zero. - // Otherwise, it is assigned the value of the immediately preceding member plus one, - // and an error occurs if the immediately preceding member is not a constant enum member - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384 /* EnumValuesComputed */; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - // Controls if error should be reported after evaluation of constant value is completed - // Can be false if another more precise error was already reported during evaluation. - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192 /* PrefixUnaryExpression */: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1 /* Literal */) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + // Only here do we need to check that the initializer is assignable to the enum type. + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192 /* PrefixUnaryExpression */: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37 /* PlusToken */: return value_1; case 38 /* MinusToken */: return -value_1; case 52 /* TildeToken */: return ~value_1; } - return undefined; - case 194 /* BinaryExpression */: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194 /* BinaryExpression */: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49 /* BarToken */: return left | right; case 48 /* AmpersandToken */: return left & right; case 46 /* GreaterThanGreaterThanToken */: return left >> right; @@ -44350,81 +45099,53 @@ var ts; case 38 /* MinusToken */: return left - right; case 42 /* PercentToken */: return left % right; } - return undefined; - case 8 /* NumericLiteral */: - checkGrammarNumericLiteral(e); - return +e.text; - case 185 /* ParenthesizedExpression */: - return evalConstant(e.expression); - case 71 /* Identifier */: - case 180 /* ElementAccessExpression */: - case 179 /* PropertyAccessExpression */: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71 /* Identifier */) { - // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. - // instead pick current enum type and later try to fetch member from the type - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9 /* StringLiteral */: + return expr.text; + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185 /* ParenthesizedExpression */: + return evaluate(expr.expression); + case 71 /* Identifier */: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180 /* ElementAccessExpression */: + case 179 /* PropertyAccessExpression */: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = expr.kind === 179 /* PropertyAccessExpression */ ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180 /* ElementAccessExpression */) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9 /* StringLiteral */) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - // expression part in ElementAccess\PropertyAccess should be either identifier or dottedName - var current = expression; - while (current) { - if (current.kind === 71 /* Identifier */) { - break; - } - else if (current.kind === 179 /* PropertyAccessExpression */) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - // allow references to constant members of other enums - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384 /* Enum */))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8 /* EnumMember */)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - // self references are illegal - if (member === propertyDecl) { - return undefined; - } - // illegal case: forward reference - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return 0; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 /* Identifier */ || + node.kind === 179 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 180 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9 /* StringLiteral */; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -44455,7 +45176,7 @@ var ts; // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -44714,6 +45435,10 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + // Don't allow to re-export something with no value side when `--isolatedModules` is set. + if (node.kind === 246 /* ExportSpecifier */ && compilerOptions.isolatedModules && !(target.flags & 107455 /* Value */)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -45436,7 +46161,7 @@ var ts; // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode return getSymbolOfNode(node.parent); } @@ -45564,7 +46289,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -45654,16 +46379,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6 /* Synthetic */) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728 /* Transient */) { if (symbol.leftSpread) { @@ -45981,7 +46706,7 @@ var ts; else if (isTypeOfKind(type, 136 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340 /* NumberLike */)) { + else if (isTypeOfKind(type, 84 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178 /* StringLike */)) { @@ -46010,7 +46735,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096 /* AddUndefined */) { - type = includeFalsyTypes(type, 2048 /* Undefined */); + type = getNullableType(type, 2048 /* Undefined */); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -46022,15 +46747,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -46116,7 +46832,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -46284,7 +46999,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1 /* FirstEmitHelper */; helper <= 8192 /* LastEmitHelper */; helper <<= 1) { + for (var helper = 1 /* FirstEmitHelper */; helper <= 16384 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455 /* Value */); @@ -46311,9 +47026,10 @@ var ts; case 256 /* Values */: return "__values"; case 512 /* Read */: return "__read"; case 1024 /* Spread */: return "__spread"; - case 2048 /* AsyncGenerator */: return "__asyncGenerator"; - case 4096 /* AsyncDelegator */: return "__asyncDelegator"; - case 8192 /* AsyncValues */: return "__asyncValues"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -47419,6 +48135,19 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242 /* ImportSpecifier */: + case 246 /* ExportSpecifier */: + if (name.parent.propertyName) { + return true; + } + // falls through + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); /// /// @@ -47556,53 +48285,63 @@ var ts; if ((kind > 0 /* FirstToken */ && kind <= 142 /* LastToken */) || kind === 169 /* ThisType */) { return node; } - switch (node.kind) { - case 206 /* SemicolonClassElement */: - case 209 /* EmptyStatement */: - case 200 /* OmittedExpression */: - case 225 /* DebuggerStatement */: - case 298 /* EndOfDeclarationMarker */: - case 247 /* MissingDeclaration */: - // No need to visit nodes with no children. - return node; + switch (kind) { // Names + case 71 /* Identifier */: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - // Signatures and Signature Elements - case 160 /* FunctionType */: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161 /* ConstructorType */: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155 /* CallSignature */: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156 /* ConstructSignature */: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150 /* MethodSignature */: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157 /* IndexSignature */: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + // Signature elements + case 145 /* TypeParameter */: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + // Type elements + case 148 /* PropertySignature */: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149 /* PropertyDeclaration */: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150 /* MethodSignature */: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151 /* MethodDeclaration */: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152 /* Constructor */: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153 /* GetAccessor */: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154 /* SetAccessor */: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155 /* CallSignature */: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156 /* ConstructSignature */: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157 /* IndexSignature */: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 159 /* TypeReference */: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 158 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159 /* TypeReference */: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160 /* FunctionType */: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161 /* ConstructorType */: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163 /* TypeLiteral */: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165 /* TupleType */: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166 /* UnionType */: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167 /* IntersectionType */: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170 /* TypeOperator */: @@ -47613,22 +48352,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - // Type Declarations - case 145 /* TypeParameter */: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - // Type members - case 148 /* PropertySignature */: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149 /* PropertyDeclaration */: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151 /* MethodDeclaration */: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152 /* Constructor */: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153 /* GetAccessor */: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154 /* SetAccessor */: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); // Binding patterns case 174 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); @@ -47667,12 +48390,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194 /* BinaryExpression */: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194 /* BinaryExpression */: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196 /* TemplateExpression */: @@ -47689,6 +48412,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204 /* MetaProperty */: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc case 205 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); @@ -47735,6 +48460,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233 /* ModuleDeclaration */: @@ -47743,6 +48472,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236 /* NamespaceExportDeclaration */: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238 /* ImportDeclaration */: @@ -47769,8 +48500,6 @@ var ts; // JSX case 249 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254 /* JsxAttributes */: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251 /* JsxOpeningElement */: @@ -47779,6 +48508,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254 /* JsxAttributes */: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256 /* JsxExpression */: @@ -47808,7 +48539,10 @@ var ts; // Transformation nodes case 296 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297 /* CommaListExpression */: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: + // No need to visit nodes with no children. return node; } } @@ -47884,6 +48618,13 @@ var ts; result = reduceNode(node.expression, cbNode, result); break; // Type member + case 148 /* PropertySignature */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -48234,6 +48975,9 @@ var ts; case 296 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; + case 297 /* CommaListExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -48856,7 +49600,7 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -50275,21 +51019,17 @@ var ts; return ts.createIdentifier("Object"); } function serializeUnionOrIntersectionType(node) { + // Note when updating logic here also update getEntityNameForDecoratorMetadata + // so that aliases can be marked as referenced var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - // If we dont have any other type already set, set the initial type - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { // One of the individual is global object, return immediately return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { // Different types if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || @@ -50819,7 +51559,12 @@ var ts; // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes // old emitter always generate 'expression' part of the name as-is. var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } /** * Transforms the value of an enum member. @@ -50894,10 +51639,12 @@ var ts; * Adds a leading VariableStatement for a enum or module declaration. */ function addVarForEnumOrModuleDeclaration(statements, node) { - // Emit a variable statement for the module. - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + // Emit a variable statement for the module. We emit top-level enums as a `var` + // declaration to avoid static errors in global scripts scripts due to redeclaration. + // enums in any other scope are emitted as a `let` declaration. + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ]); + ], currentScope.kind === 265 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -51154,7 +51901,7 @@ var ts; function visitExportDeclaration(node) { if (!node.exportClause) { // Elide a star export if the module it references does not export a value. - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { // Elide the export declaration if it does not export a value. @@ -51583,7 +52330,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -51920,7 +52667,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -51988,21 +52735,15 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield( - /*asteriskToken*/ undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), /*location*/ node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -52152,6 +52893,9 @@ var ts; return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } + function awaitAsYield(expression) { + return ts.createYield(/*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -52159,24 +52903,21 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); - var values = createAsyncValuesHelper(context, expression, /*location*/ node.expression); - var next = ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), - ts.createVariableDeclaration(result, /*type*/ undefined, next) + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), - /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), - /*incrementor*/ ts.createAssignment(result, next), - /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), + /*condition*/ ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue))), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -52187,13 +52928,7 @@ var ts; ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1 /* SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -52479,12 +53214,22 @@ var ts; /*typeArguments*/ undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); // Mark this node as originally an async function (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; @@ -52498,11 +53243,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), /*typeArguments*/ undefined, [expression]), location); } @@ -52532,7 +53277,7 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -53017,7 +53762,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -53224,7 +53969,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -54502,12 +55247,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26 /* CommaToken */, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { // none of declarations has initializer - the entire variable statement can be deleted @@ -55842,7 +56588,7 @@ var ts; if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -56276,8 +57022,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; } currentSourceFile = node; @@ -58730,7 +59475,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -59025,9 +59770,9 @@ var ts; return visitFunctionDeclaration(node); case 229 /* ClassDeclaration */: return visitClassDeclaration(node); - case 297 /* MergeDeclarationMarker */: + case 298 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 299 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: // This visitor does not descend into the tree, as export/import statements @@ -59826,9 +60571,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -60716,9 +61459,9 @@ var ts; return visitCatchClause(node); case 207 /* Block */: return visitBlock(node); - case 297 /* MergeDeclarationMarker */: + case 298 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 299 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -61200,7 +61943,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -61363,7 +62106,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299 /* Count */); + var enabledSyntaxKindFeatures = new Array(300 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -61428,7 +62171,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } /** * Enables expression substitutions in the pretty printer for the provided SyntaxKind. @@ -62377,7 +63120,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; // Contains the reference paths that needs to go in the declaration file. @@ -62413,11 +63156,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -62844,12 +63587,11 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComents*/ true); emitLines(node.statements); } - // Return a temp variable name to be used in `export default` statements. + // Return a temp variable name to be used in `export default`/`export class ... extends` statements. // The temp name will be of the form _default_counter. // Note that export default is only allowed at most once in a module, so we // do not need to keep track of created temp names. - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -62862,24 +63604,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - // Expression - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -62891,12 +63639,6 @@ var ts; // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -62969,7 +63711,7 @@ var ts; if (modifiers & 512 /* Default */) { write("default "); } - else if (node.kind !== 230 /* InterfaceDeclaration */ && !noDeclare) { + else if (node.kind !== 230 /* InterfaceDeclaration */ && needsDeclare) { write("declare "); } } @@ -63206,7 +63948,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -63305,7 +64047,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -63317,12 +64059,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named @@ -63339,7 +64075,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -63354,6 +64090,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 /* NullKeyword */ ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233 /* ModuleDeclaration */; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128 /* Abstract */)) { @@ -63361,15 +64110,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); write(" {"); writeLine(); increaseIndent(); @@ -63390,7 +64146,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, /*isImplementsList*/ false); + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); } write(" {"); writeLine(); @@ -63449,7 +64205,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */) { + else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */ || + (node.kind === 146 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -63458,7 +64215,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.kind === 229 /* ClassDeclaration */ || node.kind === 146 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -63668,6 +64425,11 @@ var ts; write("["); } else { + if (node.kind === 152 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { + write("();"); + writeLine(); + return; + } // Construct signature or constructor type write new Signature if (node.kind === 156 /* ConstructSignature */ || node.kind === 161 /* ConstructorType */) { write("new "); @@ -63974,7 +64736,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { // Declaration file, use declaration file name declFileName = referencedFile.fileName; } @@ -64158,7 +64920,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -64195,7 +64957,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -64283,7 +65045,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -64362,7 +65126,7 @@ var ts; // Strict mode reserved words // Contextual keywords if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -64580,7 +65344,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -64603,7 +65367,7 @@ var ts; case 97 /* SuperKeyword */: case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: - writeTokenText(kind); + writeTokenNode(node); return; // Expressions case 177 /* ArrayLiteralExpression */: @@ -64668,6 +65432,8 @@ var ts; // Transformation nodes case 296 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); + case 297 /* CommaListExpression */: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -64706,6 +65472,7 @@ var ts; // function emitIdentifier(node) { write(getTextOfNode(node, /*includeTrivia*/ false)); + emitTypeArguments(node, node.typeArguments); } // // Names @@ -64734,6 +65501,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -64854,7 +65622,10 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65 /* TypeLiteralMembers */); + // If the literal is empty, do not add spaces between braces. + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */); + } write("}"); } function emitArrayType(node) { @@ -64892,9 +65663,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1 /* SingleLine */) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -64905,8 +65682,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1 /* SingleLine */) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -64922,7 +65704,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432 /* ObjectBindingPatternElements */); + emitList(node, elements, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 272 /* ObjectBindingPatternElements */ : 432 /* ObjectBindingPatternElementsWithSpaceBetweenBraces */); write("}"); } } @@ -65006,7 +65788,7 @@ var ts; // check if constant enum value is integer var constantValue = ts.getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -65109,7 +65891,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -65837,6 +66619,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272 /* CommaListElements */); + } /** * Emits any prologue directives at the start of a Statement list, returning the * number of prologue directives written to the output. @@ -66118,6 +66903,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -66300,7 +67094,9 @@ var ts; if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -66580,14 +67376,17 @@ var ts; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; @@ -66814,6 +67613,90 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, + // so we'll skip ahead to the second-to-last line. + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + // Output the gutter and the actual contents of the line. + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + // Output the gutter and the error span for the line using tildes. + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -66863,6 +67746,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -66919,7 +67803,8 @@ var ts; // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2 /* Completely */) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); @@ -66978,7 +67863,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -67016,76 +67902,100 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { - // if old program state is not supplied and file does not contain locally defined ambient modules - // then the best we can do is fallback to the default logic + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. return resolveModuleNamesWorker(moduleNames, containingFile); } - // at this point we know that either + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occured during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } + // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules - // OR // - old program state is available - // OR - // - both of items above - // With this it is possible that we can tell how some module names from the initial list will be resolved - // without doing actual resolution (in particular if some name was resolved to ambient module). - // Such names should be excluded from the list of module names that will be provided to `resolveModuleNamesWorker` - // since we don't want to resolve them again. - // this is a list of modules for which we cannot predict resolution so they should be actually resolved + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ var unknownModuleNames; - // this is a list of combined results assembles from predicted and resolved results. - // Order in this list matches the order in the original list of module names `moduleNames` which is important - // so later we can split results to resolutions of modules and resolutions of module augmentations. + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ var result; - // a transient placeholder that is used to mark predicted resolution in the result list + /** A transient placeholder used to mark predicted resolution in the result list. */ var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - // module name is known to be resolved to ambient module if - // - module name is contained in the list of ambient modules that are locally declared in the file - // - in the old program module name was resolved to ambient module whose declaration is in non-modified file + // If we want to reuse resolutions more aggressively, we can refine this to check for whether the + // text of the corresponding modulenames has changed. + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file // (so the same module declaration will land in the new program) - var isKnownToResolveToAmbientModule = false; + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - // found a first module name for which result can be prediced - // this means that this module name should not be passed to `resolveModuleNamesWorker`. - // We'll use a separate list for module names that are definitely unknown. - result = new Array(moduleNames.length); - // copy all module names that appear before the current one in the list - // since they are known to be unknown - unknownModuleNames = moduleNames.slice(0, i); - } - // mark prediced resolution in the result list - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - // found unknown module name and we are already using separate list for those - add it to the list - unknownModuleNames.push(moduleName); + else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - // we've looked throught the list but have not seen any predicted resolution - // use default logic - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; - // combine results of resolutions and predicted results + // Combine results of resolutions and predicted results + if (!result) { + // There were no unresolved/ambient resolutions. + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -67094,16 +68004,15 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { // module used to be resolved to file - ignore it return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -67123,84 +68032,90 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0 /* Not */; } // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); // there is an old program, check if we can reuse its structure var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2 /* Completely */; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { + // The `newSourceFile` object was created for the new program. if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // check tripleslash references if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // check imports and module augmentations collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { // imports has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { // moduleAugmentations has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { // 'types' references has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - // file has no changes - use it as is - newSourceFile = oldSourceFile; - } // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); // try to verify results of module resolution for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -67209,12 +68124,16 @@ var ts; // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - // pass the cache of module/types resolutions from the old source file - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; } // update fileName -> file mapping for (var i = 0; i < newSourceFiles.length; i++) { @@ -67227,8 +68146,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return { @@ -67616,7 +68534,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -67647,7 +68565,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -67694,7 +68611,7 @@ var ts; } break; case 233 /* ModuleDeclaration */: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { var moduleName = node.name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: @@ -67705,7 +68622,7 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { // for global .d.ts files record name of ambient module (ambientModules || (ambientModules = [])).push(moduleName.text); } @@ -67734,45 +68651,52 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -67925,11 +68849,11 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9 /* StringLiteral */; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -67986,7 +68910,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -68084,12 +69008,12 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -68352,6 +69276,7 @@ var ts; "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -69266,57 +70191,37 @@ var ts; * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; + } + if (exclude) { + json.exclude = exclude; + } + if (files) { + json.files = files; + } + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; + } + return options; + })(); + options = ts.extend(existingOptions, options); + options.configFilePath = configFileName; // typingOptions has been deprecated and is only supported for backward compatibility purposes. // It should be removed in future releases - use typeAcquisition instead. var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); - } - if (include && !json["include"]) { - json["include"] = include; - } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; - } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } - options = ts.extend(existingOptions, options); - options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -69326,39 +70231,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - // Merge configs (copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios) - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/ undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -69389,9 +70262,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { // If no includes were specified, exclude common package folders and the outDir excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; @@ -69409,9 +70279,73 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, // Usually a string. + host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -70046,7 +70980,6 @@ var ts; case 148 /* PropertySignature */: case 261 /* PropertyAssignment */: case 262 /* ShorthandPropertyAssignment */: - case 264 /* EnumMember */: case 151 /* MethodDeclaration */: case 150 /* MethodSignature */: case 152 /* Constructor */: @@ -70063,9 +70996,11 @@ var ts; case 231 /* TypeAliasDeclaration */: case 163 /* TypeLiteral */: return 2 /* Type */; + case 264 /* EnumMember */: case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; + case 232 /* EnumDeclaration */: + return 7 /* All */; case 233 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; @@ -70082,7 +71017,7 @@ var ts; case 238 /* ImportDeclaration */: case 243 /* ExportAssignment */: case 244 /* ExportDeclaration */: - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + return 7 /* All */; // An external module can be a Value case 265 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; @@ -70241,7 +71176,7 @@ var ts; case 153 /* GetAccessor */: case 154 /* SetAccessor */: case 233 /* ModuleDeclaration */: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180 /* ElementAccessExpression */: return node.parent.argumentExpression === node; case 144 /* ComputedPropertyName */: @@ -70256,36 +71191,6 @@ var ts; ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; - /** Returns true if the position is within a comment */ - function isInsideComment(sourceFile, token, position) { - // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - // either we are 1. completely inside the comment, or 2. at the end of the comment - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - // is single line comment or just /* - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) { - return true; - } - else { - // is unterminated multi-line comment - return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ && - text.charCodeAt(comment.end - 2) === 42 /* asterisk */); - } - } - return false; - }); - } - } - ts.isInsideComment = isInsideComment; function getContainerNode(node) { while (true) { node = node.parent; @@ -70623,45 +71528,25 @@ var ts; // exit early return current; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1 /* EndOfFileToken */)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } // find the child that contains 'position' - for (var _a = 0, _b = current.getChildren(); _a < _b.length; _a++) { - var child = _b[_a]; - // all jsDocComment nodes were already visited - if (ts.isJSDocNode(child)) { + for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + if (ts.isJSDocNode(child) && !includeJsDocComment) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + continue; + } + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } @@ -70788,10 +71673,6 @@ var ts; return false; } ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, /*predicate*/ undefined); - } - ts.isInComment = isInComment; /** * returns true if the position is in between the open and close elements of an JSX expression. */ @@ -70830,13 +71711,27 @@ var ts; } ts.isInTemplateString = isInTemplateString; /** - * Returns true if the cursor at position in sourceFile is within a comment that additionally - * satisfies predicate, and false otherwise. + * Returns true if the cursor at position in sourceFile is within a comment. + * + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param predicate Additional predicate to test on the comment range. */ - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + function isInComment(sourceFile, position, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position); } + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); + function isInCommentRange(commentRanges) { + return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); + } + } + ts.isInComment = isInComment; + function isPositionInCommentRange(_a, position, text) { + var pos = _a.pos, end = _a.end, kind = _a.kind; + if (pos < position && position < end) { + return true; + } + else if (position === end) { // The end marker of a single-line comment does not include the newline character. // In the following case, we are inside a comment (^ denotes the cursor position): // @@ -70847,16 +71742,14 @@ var ts; // /* asdf */^ // // Internally, we represent the end of the comment at the newline and closing '/', respectively. - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); }); + return kind === 2 /* SingleLineCommentTrivia */ || + // true for unterminated multi-line comment + !(text.charCodeAt(end - 1) === 47 /* slash */ && text.charCodeAt(end - 2) === 42 /* asterisk */); + } + else { + return false; } - return false; } - ts.isInCommentHelper = isInCommentHelper; function hasDocComment(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); // First, we have to see if this position actually landed in a comment. @@ -70979,6 +71872,9 @@ var ts; } ts.isAccessibilityModifier = isAccessibilityModifier; function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } for (var e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { @@ -71027,25 +71923,27 @@ var ts; } ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInNonReferenceComment = isInNonReferenceComment; function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; function isTypeKeyword(kind) { switch (kind) { case 119 /* AnyKeyword */: @@ -71326,8 +72224,8 @@ var ts; // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these // as well var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; diagnostic.start = diagnostic.start - 1; } var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; @@ -71422,7 +72320,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -71431,8 +72329,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -72441,8 +73339,8 @@ var ts; continue; } var start = completePrefix.length; - var length_6 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_6))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -72733,7 +73631,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; if (requestJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; @@ -72763,14 +73661,16 @@ var ts; sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); } - // Add keywords if this is not a member completion list - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + if (hasFilteredClassMemberKeywords) { + ts.addRange(entries, classMemberKeywordCompletions); + } + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; @@ -72826,8 +73726,8 @@ var ts; var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { + var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -72917,10 +73817,11 @@ var ts; function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) { var candidates = []; var entries = []; + var uniques = ts.createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { var candidate = candidates_3[_i]; - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; @@ -72948,9 +73849,10 @@ var ts; } return undefined; } - function addStringLiteralCompletionsFromType(type, result, typeChecker) { + function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 16384 /* TypeParameter */) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; @@ -72958,16 +73860,20 @@ var ts; if (type.flags & 65536 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & 32 /* StringLiteral */) { - result.push({ - name: type.text, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, - sortText: "0" - }); + var name = type.value; + if (!uniques.has(name)) { + uniques.set(name, true); + result.push({ + name: name, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } } } function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { @@ -73032,7 +73938,7 @@ var ts; log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); // Completion not allowed inside comments, bail out if this is the case - var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { @@ -73083,7 +73989,7 @@ var ts; } } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -73171,6 +74077,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; + var hasFilteredClassMemberKeywords = false; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -73204,7 +74111,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols() { // Right of dot member completion list isGlobalCompletion = false; @@ -73255,6 +74162,7 @@ var ts; function tryGetGlobalSymbols() { var objectLikeContainer; var namedImportsOrExports; + var classLikeContainer; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); @@ -73264,6 +74172,11 @@ var ts; // try to show exported member for imported module return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + // cursor inside class declaration + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; + } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; if ((jsxContainer.kind === 250 /* JsxSelfClosingElement */) || (jsxContainer.kind === 251 /* JsxOpeningElement */)) { @@ -73437,16 +74350,16 @@ var ts; function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; - var typeForObject; + var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; - // If the object literal is being assigned to something of type 'null | { hello: string }', - // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 174 /* ObjectBindingPattern */) { @@ -73469,7 +74382,11 @@ var ts; } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = objectLikeContainer.elements; } } @@ -73480,10 +74397,6 @@ var ts; else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); @@ -73525,6 +74438,53 @@ var ts; symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); return true; } + /** + * Aggregates relevant symbols for completion in class declaration + * Relevant symbols are stored in the captured 'symbols' variable. + */ + function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + // We're looking up possible property names from parent type. + isMemberCompletion = true; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for class elements + hasFilteredClassMemberKeywords = true; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); + var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8 /* Private */; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + break; + } + } + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { + var baseClassTypeToGetPropertiesFrom = void 0; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & 32 /* Static */) { + // Use static class to get property symbols from + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32 /* Static */) ? + undefined : + ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + // List of property symbols of base type that are not private and already implemented + symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + } + } + } /** * Returns the immediate owning object literal or binding pattern of a context token, * on the condition that one exists and that the context implies completion should be given. @@ -73561,6 +74521,44 @@ var ts; } return undefined; } + function isFromClassElementDeclaration(node) { + return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetClassLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 17 /* OpenBraceToken */: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + // class c {getValue(): number; | } + case 26 /* CommaToken */: + case 25 /* SemicolonToken */: + // class c { method() { } | } + case 18 /* CloseBraceToken */: + if (ts.isClassLike(location)) { + return location; + } + break; + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent; + } + } + } + // class c { method() { } | method2() { } } + if (location && location.kind === 294 /* SyntaxList */ && ts.isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -73673,7 +74671,7 @@ var ts; containingNodeKind === 231 /* TypeAliasDeclaration */ || isFunction(containingNodeKind); case 115 /* StaticKeyword */: - return containingNodeKind === 149 /* PropertyDeclaration */; + return containingNodeKind === 149 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); case 24 /* DotDotDotToken */: return containingNodeKind === 146 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && @@ -73686,13 +74684,17 @@ var ts; return containingNodeKind === 242 /* ImportSpecifier */ || containingNodeKind === 246 /* ExportSpecifier */ || containingNodeKind === 240 /* NamespaceImport */; + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } + // falls through case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: case 89 /* FunctionKeyword */: case 104 /* VarKeyword */: - case 125 /* GetKeyword */: - case 135 /* SetKeyword */: case 91 /* ImportKeyword */: case 110 /* LetKeyword */: case 76 /* ConstKeyword */: @@ -73700,6 +74702,12 @@ var ts; case 138 /* TypeKeyword */: return true; } + // If the previous token is keyword correspoding to class member completion keyword + // there will be completion available here + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } // Previous token may have been a keyword that was converted to an identifier. switch (contextToken.getText()) { case "abstract": @@ -73742,7 +74750,7 @@ var ts; for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; @@ -73776,7 +74784,7 @@ var ts; continue; } // If this is the current item we are editing right now, do not filter it out - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; @@ -73790,12 +74798,55 @@ var ts; // TODO(jfreeman): Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); } + /** + * Filters out completion suggestions for class elements. + * + * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags + */ + function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 149 /* PropertyDeclaration */ && + m.kind !== 151 /* MethodDeclaration */ && + m.kind !== 153 /* GetAccessor */ && + m.kind !== 154 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + // Dont filter member even if the name matches if it is declared private in the list + if (ts.hasModifier(m, 8 /* Private */)) { + continue; + } + // do not filter it out if the static presence doesnt match + var mIsStatic = ts.hasModifier(m, 32 /* Static */); + var currentElementIsStatic = !!(currentClassElementModifierFlags & 32 /* Static */); + if ((mIsStatic && !currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return ts.concatenate(ts.filter(baseSymbols, function (baseProperty) { return isValidProperty(baseProperty, 8 /* Private */); }), ts.filter(implementingTypeSymbols, function (implementingProperty) { return isValidProperty(implementingProperty, 24 /* NonPublicAccessibilityModifier */); })); + function isValidProperty(propertySymbol, inValidModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } + } /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. * @@ -73807,7 +74858,7 @@ var ts; for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; // If this is the current item we are editing right now, do not filter it out - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253 /* JsxAttribute */) { @@ -73816,6 +74867,9 @@ var ts; } return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); } + function isCurrentlyEditingNode(node) { + return node.getStart() <= position && position <= node.getEnd(); + } } /** * Get the name to be display in completion from a given symbol. @@ -73868,6 +74922,27 @@ var ts; sortText: "0" }); } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 113 /* ProtectedKeyword */: + case 112 /* PrivateKeyword */: + case 117 /* AbstractKeyword */: + case 115 /* StaticKeyword */: + case 123 /* ConstructorKeyword */: + case 131 /* ReadonlyKeyword */: + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + case 120 /* AsyncKeyword */: + return true; + } + } + function isClassMemberCompletionKeywordText(text) { + return isClassMemberCompletionKeyword(ts.stringToToken(text)); + } + var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { + return isClassMemberCompletionKeywordText(entry.name); + }); function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -73884,9 +74959,9 @@ var ts; (function (ts) { var DocumentHighlights; (function (DocumentHighlights) { - function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) { + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -73898,8 +74973,8 @@ var ts; kind: ts.HighlightSpanKind.none }; } - function getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -74693,6 +75768,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { @@ -74771,11 +75849,42 @@ var ts; } }); } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 265 /* SourceFile */) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -74799,7 +75908,7 @@ var ts; } /** Calls `action` for each import, re-export, or require() in a file. */ function forEachImport(sourceFile, action) { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); @@ -74827,26 +75936,20 @@ var ts; } } }); - if (sourceFile.flags & 65536 /* JavaScriptFile */) { - // Find all 'require()' calls. - sourceFile.forEachChild(function recur(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - action(node, node.arguments[0]); - } - else { - node.forEachChild(recur); - } - }); - } } } function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; - if (decl.kind === 238 /* ImportDeclaration */ || decl.kind === 244 /* ExportDeclaration */) { - return decl; + switch (decl.kind) { + case 181 /* CallExpression */: + case 238 /* ImportDeclaration */: + case 244 /* ExportDeclaration */: + return decl; + case 248 /* ExternalModuleReference */: + return decl.parent; + default: + ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); } - ts.Debug.assert(decl.kind === 248 /* ExternalModuleReference */); - return decl.parent; } /** * Given a local reference, we might notice that it's an import/export and recursively search for references of that. @@ -74983,12 +76086,13 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + return ts.forEach(symbol.declarations, function (decl) { + if (ts.isExportAssignment(decl)) { + return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + } + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 /* Identifier */ && name.text; }); - ts.Debug.assert(!!name); - return name; } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { @@ -75035,12 +76139,13 @@ var ts; return { type: "node", node: node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; - function findReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } var out = []; + var checker = program.getTypeChecker(); for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. @@ -75051,44 +76156,46 @@ var ts; return out; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; - function getImplementationsAtPosition(checker, cancellationToken, sourceFiles, sourceFile, position) { + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(typeChecker, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 262 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(checker, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { + var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options) { + function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -75098,10 +76205,6 @@ var ts; switch (def.type) { case "symbol": { var symbol = def.symbol, node_2 = def.node; - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; @@ -75242,7 +76345,7 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } if (node.kind === 265 /* SourceFile */) { return undefined; @@ -75253,6 +76356,7 @@ var ts; return special; } } + var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); // Could not find a symbol e.g. unknown identifier if (!symbol) { @@ -75263,13 +76367,60 @@ var ts; // Can't have references to something that we have no symbol for. return undefined; } - // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; + if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleReferenceLocation(node) { + if (node.kind !== 9 /* StringLiteral */) { + return false; + } + switch (node.parent.kind) { + case 233 /* ModuleDeclaration */: + case 248 /* ExternalModuleReference */: + case 238 /* ImportDeclaration */: + case 244 /* ExportDeclaration */: + return true; + case 181 /* CallExpression */: + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false); + default: + return false; + } + } + function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 265 /* SourceFile */: + // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) + break; + case 233 /* ModuleDeclaration */: + references.push({ type: "node", node: decl.name }); + break; + default: + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + return [{ + definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, + references: references + }]; + } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { @@ -75510,7 +76661,11 @@ var ts; // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.) return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + if (container === void 0) { container = sourceFile; } + if (fullStart === void 0) { fullStart = false; } + var start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + var end = container.getEnd(); var positions = []; /// TODO: Cache symbol existence for files to save text search // Also, need to make this work for unicode escapes. @@ -75542,16 +76697,12 @@ var ts; var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { var position = possiblePositions_1[_i]; var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } // Only pick labels that are either the target label, or have a target that is the target label - if (node === targetLabel || - (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } } @@ -75561,28 +76712,27 @@ var ts; // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node && node.kind) { case 71 /* Identifier */: - return node.getWidth() === searchSymbolName.length; + return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; case 9 /* StringLiteral */: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - // For string literals we have two additional chars for the quotes - node.getWidth() === searchSymbolName.length + 2; + node.text.length === searchSymbolName.length; case 8 /* NumericLiteral */: - return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; default: return false; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); @@ -75604,10 +76754,8 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - var start = state.findInComments ? container.getFullStart() : container.getStart(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments); _i < _a.length; _i++) { + var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } @@ -75738,7 +76886,7 @@ var ts; * position of property accessing, the referenceEntry of such position will be handled in the first case. */ if (!(flags & 134217728 /* Transient */) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -76004,9 +77152,9 @@ var ts; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { - var position = possiblePositions_4[_i]; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); + for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { + var position = possiblePositions_3[_i]; var node = ts.getTouchingWord(sourceFile, position); if (!node || node.kind !== 97 /* SuperKeyword */) { continue; @@ -76058,13 +77206,13 @@ var ts; if (searchSpaceNode.kind === 265 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ @@ -76110,10 +77258,10 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } return [{ @@ -76121,8 +77269,8 @@ var ts; references: references }]; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { - for (var _i = 0, possiblePositions_5 = possiblePositions; _i < possiblePositions_5.length; _i++) { - var position = possiblePositions_5[_i]; + for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { + var position = possiblePositions_4[_i]; var node_7 = ts.getTouchingWord(sourceFile, position); if (node_7 && node_7.kind === 9 /* StringLiteral */ && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, /*isInString*/ true)); @@ -76319,20 +77467,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_5 = []; + var result_6 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -76501,17 +77649,10 @@ var ts; // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. - if (symbol.flags & 8388608 /* Alias */) { - var declaration = symbol.declarations[0]; - // Go to the original declaration for cases: - // - // (1) when the aliased symbol was declared in the location(parent). - // (2) when the aliased symbol is originating from a named import. - // - if (node.kind === 71 /* Identifier */ && - (node.parent === declaration || - (declaration.kind === 242 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 241 /* NamedImports */))) { - symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.flags & 8388608 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; } } // Because name in short-hand property assignment has two different meanings: property name and property value, @@ -76530,16 +77671,6 @@ var ts; var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } - if (ts.isJsxOpeningLikeElement(node.parent)) { - // If there are errors when trying to figure out stateless component function, just return the first declaration - // For example: - // declare function /*firstSource*/MainButton(buttonProps: ButtonProps): JSX.Element; - // declare function /*secondSource*/MainButton(linkProps: LinkProps): JSX.Element; - // declare function /*thirdSource*/MainButton(props: ButtonProps | LinkProps): JSX.Element; - // let opt =
; // Error - We get undefined for resolved signature indicating an error, then just return the first declaration - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } // If the current location we want to find its definition is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. // For example @@ -76550,16 +77681,10 @@ var ts; // function Foo(arg: Props) {} // Foo( { pr/*1*/op1: 10, prop2: true }) var element = ts.getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent)) { - var result = []; - var propertySymbols = ts.getPropertySymbolsFromContextualType(typeChecker, element); - for (var _i = 0, propertySymbols_1 = propertySymbols; _i < propertySymbols_1.length; _i++) { - var propertySymbol = propertySymbols_1[_i]; - result.push.apply(result, getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent)) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); } return getDefinitionFromSymbol(typeChecker, symbol, node); } @@ -76579,13 +77704,13 @@ var ts; return undefined; } if (type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_6 = []; + var result_7 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(/*to*/ result_7, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_6; + return result_7; } if (!type.symbol) { return undefined; @@ -76593,6 +77718,28 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from an import. + // + function shouldSkipAlias(node, declaration) { + if (node.kind !== 71 /* Identifier */) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 239 /* ImportClause */: + case 237 /* ImportEqualsDeclaration */: + return true; + case 242 /* ImportSpecifier */: + return declaration.parent.kind === 241 /* NamedImports */; + default: + return false; + } + } function getDefinitionFromSymbol(typeChecker, symbol, node) { var result = []; var declarations = symbol.getDeclarations(); @@ -76663,7 +77810,7 @@ var ts; } /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { @@ -76691,7 +77838,7 @@ var ts; function findReferenceInPosition(refs, pos) { for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } @@ -76763,6 +77910,7 @@ var ts; "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -76773,8 +77921,6 @@ var ts; "throws", "type", "typedef", - "property", - "prop", "version" ]; var jsDocTagNameCompletionEntries; @@ -77257,8 +78403,8 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_4(sourceFile); } // Remove imports when the imported declaration is already in the list and has the same name. @@ -77301,17 +78447,20 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); + } + else { + // Don't know how to add this. + return false; + } } } return true; @@ -77340,8 +78489,9 @@ var ts; var containers = []; // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -77379,6 +78529,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -77388,8 +78539,8 @@ var ts; fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -77641,8 +78792,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { // Anonymous items are never merged. return true; @@ -77731,9 +78882,9 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186 /* FunctionExpression */: @@ -77750,7 +78901,7 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -79128,138 +80279,6 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - // A partially written generic type expression is not guaranteed to have the correct syntax tree. the expression could be parsed as less than/greater than expression or a comma expression - // or some other combination depending on what the user has typed so far. For the purposes of signature help we need to consider any location after "<" as a possible generic type reference. - // To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it - // will return the generic identifier that started the expression (e.g. "foo" in "foo= 0; - }; - return TokenRangeAccess; - }()); - Shared.TokenRangeAccess = TokenRangeAccess; + var allTokens = []; + for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { + allTokens.push(token); + } var TokenValuesAccess = (function () { - function TokenValuesAccess(tks) { - this.tokens = tks && tks.length ? tks : []; + function TokenValuesAccess(tokens) { + if (tokens === void 0) { tokens = []; } + this.tokens = tokens; } TokenValuesAccess.prototype.GetTokens = function () { return this.tokens; @@ -81588,9 +82634,9 @@ var ts; TokenValuesAccess.prototype.Contains = function (token) { return this.tokens.indexOf(token) >= 0; }; + TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { this.token = token; @@ -81601,18 +82647,14 @@ var ts; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { return tokenValue === this.token; }; + TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { - var result = []; - for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { - result.push(token); - } - return result; + return allTokens; }; TokenAllAccess.prototype.Contains = function () { return true; @@ -81620,51 +82662,80 @@ var ts; TokenAllAccess.prototype.toString = function () { return "[allTokens]"; }; + TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - Shared.TokenAllAccess = TokenAllAccess; - var TokenRange = (function () { - function TokenRange(tokenAccess) { - this.tokenAccess = tokenAccess; + var TokenAllExceptAccess = (function () { + function TokenAllExceptAccess(except) { + this.except = except; } - TokenRange.FromToken = function (token) { - return new TokenRange(new TokenSingleValueAccess(token)); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - TokenRange.FromRange = function (f, to, except) { - if (except === void 0) { except = []; } - return new TokenRange(new TokenRangeAccess(f, to, except)); - }; - TokenRange.AllTokens = function () { - return new TokenRange(new TokenAllAccess()); - }; - TokenRange.prototype.GetTokens = function () { - return this.tokenAccess.GetTokens(); - }; - TokenRange.prototype.Contains = function (token) { - return this.tokenAccess.Contains(token); - }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); - }; - return TokenRange; + TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; + return TokenAllExceptAccess; }()); - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); - TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]); - TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */]); - Shared.TokenRange = TokenRange; + var TokenRange; + (function (TokenRange) { + function FromToken(token) { + return new TokenSingleValueAccess(token); + } + TokenRange.FromToken = FromToken; + function FromTokens(tokens) { + return new TokenValuesAccess(tokens); + } + TokenRange.FromTokens = FromTokens; + function FromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); + } + TokenRange.FromRange = FromRange; + function AnyExcept(token) { + return new TokenAllExceptAccess(token); + } + TokenRange.AnyExcept = AnyExcept; + TokenRange.Any = new TokenAllAccess(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3 /* MultiLineCommentTrivia */])); + TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); + TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ + 92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */ + ]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ + 43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */ + ]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ + 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, + 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ + ]); + TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); + TokenRange.TypeNames = TokenRange.FromTokens([ + 71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, + 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */ + ]); + })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -81689,6 +82760,8 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); + var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + this.rulesMap = formatting.RulesMap.create(activeRules); } RulesProvider.prototype.getRuleName = function (rule) { return this.globalRules.getRuleName(rule); @@ -81704,123 +82777,9 @@ var ts; }; RulesProvider.prototype.ensureUpToDate = function (options) { if (!this.options || !ts.compareDataObjects(this.options, options)) { - var activeRules = this.createActiveRules(options); - var rulesMap = formatting.RulesMap.create(activeRules); - this.activeRules = activeRules; - this.rulesMap = rulesMap; this.options = ts.clone(options); } }; - RulesProvider.prototype.createActiveRules = function (options) { - var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterConstructor) { - rules.push(this.globalRules.SpaceAfterConstructor); - } - else { - rules.push(this.globalRules.NoSpaceAfterConstructor); - } - if (options.insertSpaceAfterCommaDelimiter) { - rules.push(this.globalRules.SpaceAfterComma); - } - else { - rules.push(this.globalRules.NoSpaceAfterComma); - } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { - rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); - } - else { - rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); - } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { - rules.push(this.globalRules.SpaceAfterKeywordInControl); - } - else { - rules.push(this.globalRules.NoSpaceAfterKeywordInControl); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { - rules.push(this.globalRules.SpaceAfterOpenParen); - rules.push(this.globalRules.SpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenParen); - rules.push(this.globalRules.NoSpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { - rules.push(this.globalRules.SpaceAfterOpenBracket); - rules.push(this.globalRules.SpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBracket); - rules.push(this.globalRules.NoSpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true - // so if the option is undefined, we should treat it as true as well - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { - rules.push(this.globalRules.SpaceAfterOpenBrace); - rules.push(this.globalRules.SpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBrace); - rules.push(this.globalRules.NoSpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { - rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); - } - else { - rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { - rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); - } - if (options.insertSpaceAfterSemicolonInForStatements) { - rules.push(this.globalRules.SpaceAfterSemicolonInFor); - } - else { - rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); - } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { - rules.push(this.globalRules.SpaceBeforeBinaryOperator); - rules.push(this.globalRules.SpaceAfterBinaryOperator); - } - else { - rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); - rules.push(this.globalRules.NoSpaceAfterBinaryOperator); - } - if (options.insertSpaceBeforeFunctionParenthesis) { - rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl); - } - else { - rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl); - } - if (options.placeOpenBraceOnNewLineForControlBlocks) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); - } - if (options.placeOpenBraceOnNewLineForFunctions) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); - rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); - } - if (options.insertSpaceAfterTypeAssertion) { - rules.push(this.globalRules.SpaceAfterTypeAssertion); - } - else { - rules.push(this.globalRules.NoSpaceAfterTypeAssertion); - } - rules = rules.concat(this.globalRules.LowPriorityCommonRules); - return rules; - }; return RulesProvider; }()); formatting.RulesProvider = RulesProvider; @@ -82074,7 +83033,7 @@ var ts; } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { // formatting context is used by rules provider - var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRangeHasError; var previousRange; var previousParent; @@ -82171,7 +83130,7 @@ var ts; // falls through case 149 /* PropertyDeclaration */: case 146 /* Parameter */: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -83069,9 +84028,7 @@ var ts; if (node.kind === 20 /* CloseParenToken */) { return -1 /* Unknown */; } - if (node.parent && (node.parent.kind === 181 /* CallExpression */ || - node.parent.kind === 182 /* NewExpression */) && - node.parent.expression !== node) { + if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { @@ -83665,7 +84622,7 @@ var ts; }()); textChanges.ChangeTracker = ChangeTracker; function getNonformattedText(node, sourceFile, newLine) { - var options = { newLine: newLine, target: sourceFile.languageVersion }; + var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); printer.writeNode(3 /* Unspecified */, node, sourceFile, writer); @@ -83694,27 +84651,8 @@ var ts; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } - var nullTransformationContext = { - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: function () { return undefined; }, - getCompilerOptions: ts.notImplemented, - getEmitHost: ts.notImplemented, - getEmitResolver: ts.notImplemented, - hoistFunctionDeclaration: ts.noop, - hoistVariableDeclaration: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop - }; function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // create proxy node for non synthesized nodes var newNode = ts.nodeIsSynthesized(visited) ? visited @@ -83759,6 +84697,16 @@ var ts; setEnd(nodes, _this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; } Writer.prototype.setLastNonTriviaPosition = function (s, force) { if (force || !isTrivia(s)) { @@ -83827,14 +84775,14 @@ var ts; var codefix; (function (codefix) { var codeFixes = []; - function registerCodeFix(action) { - ts.forEach(action.errorCodes, function (error) { + function registerCodeFix(codeFix) { + ts.forEach(codeFix.errorCodes, function (error) { var fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } codefix.registerCodeFix = registerCodeFix; @@ -83858,6 +84806,51 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + // A map with the refactor code as key, the refactor itself as value + // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want + var refactors = ts.createMap(); + function registerRefactor(refactor) { + refactors.set(refactor.name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + var results; + var refactorList = []; + refactors.forEach(function (refactor) { + refactorList.push(refactor); + }); + for (var _i = 0, refactorList_1 = refactorList; _i < refactorList_1.length; _i++) { + var refactor_2 = refactorList_1[_i]; + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor_2.isApplicable(context)) { + (results || (results = [])).push({ name: refactor_2.name, description: refactor_2.description }); + } + } + return results; + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getRefactorCodeActions(context, refactorName) { + var result; + var refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + var codeActions = refactor.getCodeActions(context); + if (codeActions) { + ts.addRange((result || (result = [])), codeActions); + } + return result; + } + refactor_1.getRefactorCodeActions = getRefactorCodeActions; + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -83924,7 +84917,8 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { @@ -84014,7 +85008,7 @@ var ts; /*dotDotDotToken*/ undefined, "x", /*questionToken*/ undefined, stringTypeNode, /*initializer*/ undefined); - var indexSignature = ts.createIndexSignatureDeclaration( + var indexSignature = ts.createIndexSignature( /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); @@ -84031,6 +85025,60 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + function getActionsForCorrectSpelling(context) { + var sourceFile = context.sourceFile; + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + var node = ts.getTokenAtPosition(sourceFile, context.span.start); + var checker = context.program.getTypeChecker(); + var suggestion; + if (node.kind === 71 /* Identifier */ && ts.isPropertyAccessExpression(node.parent)) { + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else { + var meaning = ts.getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4 /* Namespace */) { + flags |= 1920 /* Namespace */; + } + if (meaning & 2 /* Type */) { + flags |= 793064 /* Type */; + } + if (meaning & 1 /* Value */) { + flags |= 107455 /* Value */; + } + return flags; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -84232,131 +85280,135 @@ var ts; } switch (token.kind) { case 71 /* Identifier */: - switch (token.parent.kind) { - case 226 /* VariableDeclaration */: - switch (token.parent.parent.parent.kind) { - case 214 /* ForStatement */: - var forStatement = token.parent.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(token.parent); - } - case 216 /* ForOfStatement */: - var forOfStatement = token.parent.parent.parent; - if (forOfStatement.initializer.kind === 227 /* VariableDeclarationList */) { - var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); - } - break; - case 215 /* ForInStatement */: - // There is no valid fix in the case of: - // for .. in - return undefined; - case 260 /* CatchClause */: - var catchClause = token.parent.parent; - var parameter = catchClause.variableDeclaration.getChildren()[0]; - return deleteNode(parameter); - default: - var variableStatement = token.parent.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); - } - else { - return deleteNodeInList(token.parent); - } - } - // TODO: #14885 - // falls through - case 145 /* TypeParameter */: - var typeParameters = token.parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); - if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { - return deleteRange(typeParameters); - } - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); - if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); - } - else { - return deleteNodeInList(token.parent); - } - case 146 /* Parameter */: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } - // handle case where 'import a = A;' - case 237 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); - return deleteNode(importEquals); - case 242 /* ImportSpecifier */: - var namedImports = token.parent.parent; - if (namedImports.elements.length === 1) { - // Only 1 import and it is unused. So the entire declaration should be removed. - var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); - return deleteNode(importSpec); - } - else { - // delete import specifier - return deleteNodeInList(token.parent); - } - // handle case where "import d, * as ns from './file'" - // or "'import {a, b as ns} from './file'" - case 239 /* ImportClause */: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); - return deleteNode(importDecl); - } - else { - // import |d,| * as ns from './file' - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { - // shift first non-whitespace position after comma to the start position of the node - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); - } - else { - return deleteNode(importClause.name); - } - } - case 240 /* NamespaceImport */: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { - var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); - return deleteNode(importDecl); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); - if (previousToken && previousToken.kind === 26 /* CommaToken */) { - var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); - } - return deleteRange(namespaceImport); - } - } - break; + return deleteIdentifier(); case 149 /* PropertyDeclaration */: case 240 /* NamespaceImport */: return deleteNode(token.parent); + default: + return deleteDefault(); } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + function deleteIdentifier() { + switch (token.parent.kind) { + case 226 /* VariableDeclaration */: + return deleteVariableDeclaration(token.parent); + case 145 /* TypeParameter */: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); + if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { + return deleteRange(typeParameters); + } + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); + if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { + return deleteRange(typeParameters); + } + return deleteNodeRange(previousToken, nextToken); + } + else { + return deleteNodeInList(token.parent); + } + case 146 /* Parameter */: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return deleteNode(token.parent); + } + else { + return deleteNodeInList(token.parent); + } + // handle case where 'import a = A;' + case 237 /* ImportEqualsDeclaration */: + var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); + return deleteNode(importEquals); + case 242 /* ImportSpecifier */: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + // Only 1 import and it is unused. So the entire declaration should be removed. + var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); + return deleteNode(importSpec); + } + else { + // delete import specifier + return deleteNodeInList(token.parent); + } + // handle case where "import d, * as ns from './file'" + // or "'import {a, b as ns} from './file'" + case 239 /* ImportClause */: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); + return deleteNode(importDecl); + } + else { + // import |d,| * as ns from './file' + var start_4 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 26 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); + } + else { + return deleteNode(importClause.name); + } + } + case 240 /* NamespaceImport */: + var namespaceImport = token.parent; + if (namespaceImport.name === token && !namespaceImport.parent.name) { + var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); + return deleteNode(importDecl); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); + if (previousToken && previousToken.kind === 26 /* CommaToken */) { + var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); + return deleteRange({ pos: startPosition, end: namespaceImport.end }); + } + return deleteRange(namespaceImport); + } + default: + return deleteDefault(); + } } - else { - return undefined; + // token.parent is a variableDeclaration + function deleteVariableDeclaration(varDecl) { + switch (varDecl.parent.parent.kind) { + case 214 /* ForStatement */: + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return deleteNode(forInitializer); + } + else { + return deleteNodeInList(varDecl); + } + case 216 /* ForOfStatement */: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 227 /* VariableDeclarationList */); + var forOfInitializer = forOfStatement.initializer; + return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + case 215 /* ForInStatement */: + // There is no valid fix in the case of: + // for .. in + return undefined; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return deleteNode(variableStatement); + } + else { + return deleteNodeInList(varDecl); + } + } } function deleteNode(n) { return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); @@ -84388,6 +85440,15 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ], + getCodeActions: getImportCodeActions + }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; @@ -84485,400 +85546,393 @@ var ts; }; return ImportCodeActionMap; }()); - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - // this is a module id -> module import declaration map - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); - return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true); + function getImportCodeActions(context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + // this is a module id -> module import declaration map + var cachedImportDeclarations = []; + var lastImportDeclaration; + var currentTokenMeaning = ts.getMeaningFromLocation(token); + if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); + return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true); + } + var candidateModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + candidateModules.push(otherSourceFile.symbol); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); + } + for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { + var moduleSymbol = candidateModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); } } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - // check if this symbol is already used - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (cached) { + return cached; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 238 /* ImportDeclaration */) { + return node; } - } - // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); - } - } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + if (node.kind === 237 /* ImportEqualsDeclaration */) { + return node; } + node = node.parent; } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238 /* ImportDeclaration */) { - return node; + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608 /* Alias */) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + // With an existing import statement, there are more than one actions the user can do. + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + if (declaration.kind === 238 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { + // case: + // import * as ns from "foo" + namespaceImportDeclaration = declaration; } - if (node.kind === 237 /* ImportEqualsDeclaration */) { - return node; + else { + // cases: + // import default from "foo" + // import { bar } from "foo" or combination with the first one + // import "foo" + namedImportDeclaration = declaration; } - node = node.parent; + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + // case: + // import foo = require("foo") + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - return undefined; } - } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608 /* Alias */) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); } - return ts.getSymbolId(symbol); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; - } - function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - // With an existing import statement, there are more than one actions the user can do. - return getCodeActionsForExistingImport(existingDeclarations); + if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + /** + * If the existing import declaration already has a named import list, just + * insert the identifier into that list. + */ + var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); } else { - return [getCodeActionForNewImport()]; + // we need to create a new import statement, but the existing module specifier can be reused. + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - // It is possible that multiple import statements with the same specifier exist in the file. - // e.g. - // - // import * as ns from "foo"; - // import { member1, member2 } from "foo"; - // - // member3/**/ <-- cusor here - // - // in this case we should provie 2 actions: - // 1. change "member3" to "ns.member3" - // 2. add "member3" to the second import statement's import list - // and it is up to the user to decide which one fits best. - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; - if (declaration.kind === 238 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { - // case: - // import * as ns from "foo" - namespaceImportDeclaration = declaration; - } - else { - // cases: - // import default from "foo" - // import { bar } from "foo" or combination with the first one - // import "foo" - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - // case: - // import foo = require("foo") - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { + return declaration.moduleReference.expression.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var importList = importClause.namedBindings; + var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); + // case 1: + // original text: import default from "module" + // change to: import default, { name } from "module" + // case 2: + // original text: import {} from "module" + // change to: import { name } from "module" + if (!importList || importList.elements.length === 0) { + var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); + return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - /** - * If the existing import declaration already has a named import list, just - * insert the identifier into that list. - */ - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + /** + * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element + * import { + * foo + * } from "./module"; + */ + return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 238 /* ImportDeclaration */) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); } else { - // we need to create a new import statement, but the existing module specifier can be reused. - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + namespacePrefix = declaration.name.getText(); } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { - return declaration.moduleReference.expression.getText(); + namespacePrefix = ts.stripQuotes(namespacePrefix); + /** + * Cases: + * import * as ns from "mod" + * import default, * as ns from "mod" + * import ns = require("mod") + * + * Because there is no import list, we alter the reference to include the + * namespace instead of altering the import declaration. For example, "foo" would + * become "ns.foo" + */ + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!lastImportDeclaration) { + // insert after any existing imports + for (var i = sourceFile.statements.length - 1; i >= 0; i--) { + var statement = sourceFile.statements[i]; + if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { + lastImportDeclaration = statement; + break; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); - // case 1: - // original text: import default from "module" - // change to: import default, { name } from "module" - // case 2: - // original text: import {} from "module" - // change to: import { name } from "module" - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); - } - /** - * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element - * import { - * foo - * } from "./module"; - */ - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238 /* ImportDeclaration */) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - /** - * Cases: - * import * as ns from "mod" - * import default, * as ns from "mod" - * import ns = require("mod") - * - * Because there is no import list, we alter the reference to include the - * namespace instead of altering the import declaration. For example, "foo" would - * become "ns.foo" - */ - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - // insert after any existing imports - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { - lastImportDeclaration = statement; - break; - } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var changeTracker = createChangeTracker(); + var importClause = isDefault + ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) + : isNamespaceImport + ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(name))) + : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))])); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + if (!lastImportDeclaration) { + changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); + } + // if this file doesn't have any import statements, insert an import statement and then insert a new line + // between the only import statement and user code. Otherwise just insert the statement because chances + // are there are already a new line seperating code and import statements. + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.fileName; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { + return moduleSymbol.name; } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) - : isNamespaceImport - ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))])); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - // if this file doesn't have any import statements, insert an import statement and then insert a new line - // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line seperating code and import statements. - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { - return moduleSymbol.name; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { return undefined; } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); + if (!relativeName) { + return undefined; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { - return undefined; - } - var relativeFileName; - if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { - // if node_modules folder is in this folder or any of its parent folder, no need to keep it. - relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); - } - else { - relativeFileName = getRelativePath(moduleFileName, sourceDirectory); - } - relativeFileName = ts.removeFileExtension(relativeFileName); - if (ts.endsWith(relativeFileName, "/index")) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } - else { - try { - var moduleDirectory = ts.getDirectoryPath(moduleFileName); - var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); - if (packageJsonContent) { - var mainFile = packageJsonContent.main || packageJsonContent.typings; - if (mainFile) { - var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; + } } - catch (e) { } } - return relativeFileName; } + return relativeName; } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); } } return undefined; } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } } - return fileName; } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; - } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + // if node_modules folder is in this folder or any of its parent folder, no need to keep it. + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; } } - } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); - } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = getRelativePathIfInDirectory(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } } } - }); + function createChangeTracker() { + return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + } + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -85010,7 +86064,7 @@ var ts; } var declaration = declarations[0]; // Clone name to remove leading trivia. - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -85068,7 +86122,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -85124,7 +86178,7 @@ var ts; /*returnType*/ undefined); } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethodDeclaration( + return ts.createMethod( /*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } @@ -85147,6 +86201,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /// /// /// @@ -85156,6 +86211,188 @@ var ts; /// /// /// +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions: getCodeActions, + isApplicable: isApplicable + }; + refactor.registerRefactor(convertFunctionToES6Class); + function isApplicable(context) { + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + return symbol && symbol.flags & 16 /* Function */ && symbol.members && symbol.members.size > 0; + } + function getCodeActions(context) { + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + return []; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 228 /* FunctionDeclaration */: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 226 /* VariableDeclaration */: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, /*inList*/ true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return []; + } + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { + var deleteCallback = deletes_1[_i]; + deleteCallback(); + } + return [{ + description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + // Parent node has already been deleted; do nothing + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); + } + else { + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); + } + } + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + // all instance members are stored in the "member" array of symbol + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, /*modifiers*/ undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + // all static members are stored in the "exports" array of symbol + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + // Right now the only thing we can convert are function expressions - other values shouldn't get + // transformed. We can update this once ES public class properties are available. + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + // both properties and methods are bound as property symbols + if (!(symbol.flags & 4 /* Property */)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 /* ExpressionStatement */ + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 186 /* FunctionExpression */: + var functionExpression = assignmentBinaryExpression.right; + return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + case 187 /* ArrowFunction */: + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 207 /* Block */) { + bodyBlock = arrowFunctionBody; + } + else { + var expression = arrowFunctionBody; + bodyBlock = ts.createBlock([ts.createReturn(expression)]); + } + return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + default: + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + return ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 186 /* FunctionExpression */) { + return undefined; + } + if (node.name.kind !== 71 /* Identifier */) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/// /// /// /// @@ -85182,11 +86419,15 @@ var ts; /// /// /// +/// /// +/// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; + /* @internal */ + var ruleProvider; function createNode(kind, pos, end, parent) { var node = kind >= 143 /* FirstNode */ ? new NodeObject(kind, pos, end) : kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : @@ -85571,13 +86812,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_7 !== undefined) { - return result_7; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_8 = getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - var expr = declaration.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var expr = name.expression; if (expr.kind === 179 /* PropertyAccessExpression */) { return expr.name.text; } @@ -85962,7 +87204,7 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - var ruleProvider; + ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -85987,10 +87229,6 @@ var ts; return sourceFile; } function getRuleProvider(options) { - // Ensure rules are initialized and up to date wrt to formatting options - if (!ruleProvider) { - ruleProvider = new ts.formatting.RulesProvider(); - } ruleProvider.ensureUpToDate(options); return ruleProvider; } @@ -86283,7 +87521,7 @@ var ts; /// Goto implementation function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { @@ -86300,7 +87538,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); @@ -86333,11 +87571,11 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { @@ -86640,8 +87878,7 @@ var ts; var matchPosition = matchArray.index + preamble.length; // OK, we have found a match in the file. This is only an acceptable match if // it is contained within a comment. - var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!ts.isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInComment(sourceFile, matchPosition)) { continue; } var descriptor = undefined; @@ -86729,11 +87966,35 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file, positionOrRange, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken: cancellationToken + }; + } + function getApplicableRefactors(fileName, positionOrRange) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getApplicableRefactors: getApplicableRefactors, + getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -86859,20 +88120,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = ts.getTextOfPropertyName(node.name); if (name && contextualType) { - var result_8 = []; + var result_9 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_8.push(symbol); + result_9.push(symbol); } }); - return result_8; + return result_9; } if (symbol) { - result_8.push(symbol); - return result_8; + result_9.push(symbol); + return result_9; } } return undefined; @@ -88130,6 +89391,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations @@ -88304,3 +89568,5 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = "2.4"; + +//# sourceMappingURL=typescriptServices.js.map diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index f610c4fd273..554dc3bcaca 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -25,12 +25,449 @@ var __extends = (this && this.__extends) || (function () { })(); var ts; (function (ts) { + var SyntaxKind; + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; + SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; + SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; + SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; + SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 126] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 127] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 128] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 129] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 130] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 131] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 132] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 133] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 134] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 135] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 136] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 137] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 138] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 139] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 140] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 141] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 142] = "OfKeyword"; + SyntaxKind[SyntaxKind["QualifiedName"] = 143] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 144] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["TypeParameter"] = 145] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 146] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 147] = "Decorator"; + SyntaxKind[SyntaxKind["PropertySignature"] = 148] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 149] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 150] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 151] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 152] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 153] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 154] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 155] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 156] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 157] = "IndexSignature"; + SyntaxKind[SyntaxKind["TypePredicate"] = 158] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 159] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 160] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 161] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 162] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 163] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 164] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 165] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 166] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 167] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 168] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 169] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 170] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 171] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 172] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 173] = "LiteralType"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 174] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 175] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 176] = "BindingElement"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 177] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 178] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 179] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 180] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 181] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 182] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 183] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 184] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 185] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 186] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 187] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 188] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 189] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 190] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 191] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 192] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 193] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 194] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 195] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 196] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 197] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 198] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 199] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 200] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 201] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 202] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 203] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 204] = "MetaProperty"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 205] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 206] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["Block"] = 207] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 208] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 209] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 210] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 211] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 212] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 213] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 214] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 215] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 216] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 217] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 218] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 219] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 220] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 221] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 222] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 223] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 224] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 225] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 226] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 227] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 228] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 229] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 230] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 231] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 232] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 233] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 234] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 235] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 236] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 237] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 238] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 239] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 240] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 241] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 242] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 243] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 244] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 245] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 246] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 247] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 248] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["JsxElement"] = 249] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 250] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 251] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 252] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 253] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 254] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 255] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 256] = "JsxExpression"; + SyntaxKind[SyntaxKind["CaseClause"] = 257] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 258] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 259] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 260] = "CatchClause"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 261] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 262] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 263] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["EnumMember"] = 264] = "EnumMember"; + SyntaxKind[SyntaxKind["SourceFile"] = 265] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 266] = "Bundle"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 267] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 268] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 269] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 270] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 271] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 272] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 273] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 274] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 275] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 276] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 277] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 278] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 279] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 280] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 281] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 282] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 284] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 285] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 286] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 287] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 288] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 289] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 290] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 291] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocLiteralType"] = 293] = "JSDocLiteralType"; + SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; + SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 142] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 158] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 173] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = 142] = "LastToken"; + SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; + SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; + SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 143] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 267] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 283] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode"; + })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); + var NodeFlags; + (function (NodeFlags) { + NodeFlags[NodeFlags["None"] = 0] = "None"; + NodeFlags[NodeFlags["Let"] = 1] = "Let"; + NodeFlags[NodeFlags["Const"] = 2] = "Const"; + NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; + NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; + NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; + NodeFlags[NodeFlags["ContextFlags"] = 96256] = "ContextFlags"; + NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; + })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); + var ModifierFlags; + (function (ModifierFlags) { + ModifierFlags[ModifierFlags["None"] = 0] = "None"; + ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; + ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; + ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; + ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; + ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; + ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; + ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; + ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; + ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; + ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; + ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; + ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); + var JsxFlags; + (function (JsxFlags) { + JsxFlags[JsxFlags["None"] = 0] = "None"; + JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; + JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; + })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); + var RelationComparisonResult; + (function (RelationComparisonResult) { + RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; + RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; + RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; + })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); + var GeneratedIdentifierKind; + (function (GeneratedIdentifierKind) { + GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; + })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var NumericLiteralFlags; + (function (NumericLiteralFlags) { + NumericLiteralFlags[NumericLiteralFlags["None"] = 0] = "None"; + NumericLiteralFlags[NumericLiteralFlags["Scientific"] = 2] = "Scientific"; + NumericLiteralFlags[NumericLiteralFlags["Octal"] = 4] = "Octal"; + NumericLiteralFlags[NumericLiteralFlags["HexSpecifier"] = 8] = "HexSpecifier"; + NumericLiteralFlags[NumericLiteralFlags["BinarySpecifier"] = 16] = "BinarySpecifier"; + NumericLiteralFlags[NumericLiteralFlags["OctalSpecifier"] = 32] = "OctalSpecifier"; + NumericLiteralFlags[NumericLiteralFlags["BinaryOrOctalSpecifier"] = 48] = "BinaryOrOctalSpecifier"; + })(NumericLiteralFlags = ts.NumericLiteralFlags || (ts.NumericLiteralFlags = {})); + var FlowFlags; + (function (FlowFlags) { + FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; + FlowFlags[FlowFlags["Start"] = 2] = "Start"; + FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel"; + FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel"; + FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; + FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; + FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; + FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; + FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; + FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; + FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; + FlowFlags[FlowFlags["Label"] = 12] = "Label"; + FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; + })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); var OperationCanceledException = (function () { function OperationCanceledException() { } return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -40,13 +477,60 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + var TypeFormatFlags; + (function (TypeFormatFlags) { + TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 2] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 4] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 8] = "WriteArrowStyleSignature"; + TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 16] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 64] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 2048] = "SuppressAnyReturnType"; + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 4096] = "AddUndefined"; + })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var SymbolFormatFlags; + (function (SymbolFormatFlags) { + SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; + SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; + SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); + var SymbolAccessibility; + (function (SymbolAccessibility) { + SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; + SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; + SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; + })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + var SyntheticSymbolKind; + (function (SyntheticSymbolKind) { + SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; + SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; + })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); + var TypePredicateKind; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; @@ -61,6 +545,196 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var SymbolFlags; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; + SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; + SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags[SymbolFlags["ExportType"] = 2097152] = "ExportType"; + SymbolFlags[SymbolFlags["ExportNamespace"] = 4194304] = "ExportNamespace"; + SymbolFlags[SymbolFlags["Alias"] = 8388608] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 16777216] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 33554432] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 67108864] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 134217728] = "Transient"; + SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; + SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; + SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; + SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; + SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 107454] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 899519] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792968] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 106639] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["AliasExcludes"] = 8388608] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 8914931] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; + SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["Export"] = 7340032] = "Export"; + SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; + SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; + })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + var CheckFlags; + (function (CheckFlags) { + CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; + CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; + CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod"; + CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; + CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; + CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; + CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; + CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + var NodeCheckFlags; + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; + NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; + NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var TypeFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 1] = "Any"; + TypeFlags[TypeFlags["String"] = 2] = "String"; + TypeFlags[TypeFlags["Number"] = 4] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; + TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; + TypeFlags[TypeFlags["Void"] = 1024] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 4096] = "Null"; + TypeFlags[TypeFlags["Never"] = 8192] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 32768] = "Object"; + TypeFlags[TypeFlags["Union"] = 65536] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 131072] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 262144] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 524288] = "IndexedAccess"; + TypeFlags[TypeFlags["FreshLiteral"] = 1048576] = "FreshLiteral"; + TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; + TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; + TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; + TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; + TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; + TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; + TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; + TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; + TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; + TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; + })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + var ObjectFlags; + (function (ObjectFlags) { + ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; + ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; + ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; + ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; + ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; + ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; + ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; + ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; + ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; + ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + var SignatureKind; + (function (SignatureKind) { + SignatureKind[SignatureKind["Call"] = 0] = "Call"; + SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; + })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + var IndexKind; + (function (IndexKind) { + IndexKind[IndexKind["String"] = 0] = "String"; + IndexKind[IndexKind["Number"] = 1] = "Number"; + })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + var SpecialPropertyAssignmentKind; + (function (SpecialPropertyAssignmentKind) { + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -81,6 +755,179 @@ var ts; ModuleKind[ModuleKind["System"] = 4] = "System"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit[JsxEmit["None"] = 0] = "None"; + JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; + JsxEmit[JsxEmit["React"] = 2] = "React"; + JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; + })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); + var ScriptKind; + (function (ScriptKind) { + ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; + ScriptKind[ScriptKind["JS"] = 1] = "JS"; + ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; + ScriptKind[ScriptKind["TS"] = 3] = "TS"; + ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; + ScriptKind[ScriptKind["External"] = 5] = "External"; + })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; + ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; + ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; + ScriptTarget[ScriptTarget["ESNext"] = 5] = "ESNext"; + ScriptTarget[ScriptTarget["Latest"] = 5] = "Latest"; + })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); + var LanguageVariant; + (function (LanguageVariant) { + LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; + LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; + })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); + var DiagnosticStyle; + (function (DiagnosticStyle) { + DiagnosticStyle[DiagnosticStyle["Simple"] = 0] = "Simple"; + DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; + })(DiagnosticStyle = ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); + var WatchDirectoryFlags; + (function (WatchDirectoryFlags) { + WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; + WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; + })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + var CharacterCodes; + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; + CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; + CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; + CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); var Extension; (function (Extension) { Extension[Extension["Ts"] = 0] = "Ts"; @@ -90,6 +937,126 @@ var ts; Extension[Extension["Jsx"] = 4] = "Jsx"; Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; })(Extension = ts.Extension || (ts.Extension = {})); + var TransformFlags; + (function (TransformFlags) { + TransformFlags[TransformFlags["None"] = 0] = "None"; + TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; + TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; + TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; + TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; + TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; + TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; + TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 540087617] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + var EmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; + EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; + EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; + EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; + EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; + EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); + var ExternalEmitHelpers; + (function (ExternalEmitHelpers) { + ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; + ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; + ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; + ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; + ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; + ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; + ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; + ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; + ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; + ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; + ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; + })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); + var EmitHint; + (function (EmitHint) { + EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; + EmitHint[EmitHint["Expression"] = 1] = "Expression"; + EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; + EmitHint[EmitHint["Unspecified"] = 3] = "Unspecified"; + })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -155,6 +1122,12 @@ var ts; ts.version = "2.4.0"; })(ts || (ts = {})); (function (ts) { + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; function createDictionaryObject() { @@ -288,6 +1261,12 @@ var ts; return getCanonicalFileName(nonCanonicalizedPath); } ts.toPath = toPath; + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); function length(array) { return array ? array.length : 0; } @@ -325,6 +1304,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; function every(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -529,6 +1517,28 @@ var ts; return result; } ts.flatMap = flatMap; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1553,6 +2563,10 @@ var ts; return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -1821,6 +2835,13 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + var ExtensionPriority; + (function (ExtensionPriority) { + ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; + ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; + ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; + ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; + })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { @@ -1905,6 +2926,13 @@ var ts; getTypeConstructor: function () { return Type; }, getSignatureConstructor: function () { return Signature; } }; + var AssertionLevel; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); var Debug; (function (Debug) { Debug.currentAssertionLevel = 0; @@ -2224,6 +3252,11 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); function fileSystemEntryExists(path, entryKind) { try { var stat = _fs.statSync(path); @@ -2589,6 +3622,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -2696,7 +3730,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -2891,6 +3925,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3186,6 +4228,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -3231,6 +4274,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -3312,6 +4357,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -3860,9 +4908,10 @@ var ts; } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -5022,6 +6071,7 @@ var ts; "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -5873,49 +6923,28 @@ var ts; if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + if (exclude) { + json.exclude = exclude; } - if (include && !json["include"]) { - json["include"] = include; + if (files) { + json.files = files; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } + return options; + })(); options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -5925,37 +6954,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -5986,9 +6985,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; @@ -6005,9 +7001,66 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -6455,12 +7508,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -6744,6 +7796,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -6877,12 +7931,18 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -6912,7 +7972,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -7646,6 +8705,9 @@ var ts; _this.log.writeLine("Updating " + TypesRegistryPackageName + " npm package..."); } _this.execSync(_this.npmPath + " install " + TypesRegistryPackageName, { cwd: globalTypingsCacheLocation, stdio: "ignore" }); + if (_this.log.isEnabled()) { + _this.log.writeLine("Updated " + TypesRegistryPackageName + " npm package"); + } } catch (e) { if (_this.log.isEnabled()) { @@ -7729,3 +8791,5 @@ var ts; })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); + +//# sourceMappingURL=typingsInstaller.js.map diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 4897c1e269f..ba0496ee789 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -149,7 +149,7 @@ namespace ts { inStrictMode = bindInStrictMode(file, opts); classifiableNames = createMap(); symbolCount = 0; - skipTransformFlagAggregation = isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = objectAllocator.getSymbolConstructor(); @@ -182,7 +182,7 @@ namespace ts { return bindSourceFile; function bindInStrictMode(file: SourceFile, opts: CompilerOptions): boolean { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { // bind in strict mode source files with alwaysStrict option return true; } @@ -221,18 +221,19 @@ namespace ts { // other kinds of value declarations take precedence over modules symbol.valueDeclaration = node; } - } + } } // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node: Declaration): string { - if (node.name) { + const name = getNameOfDeclaration(node); + if (name) { if (isAmbientModule(node)) { - return isGlobalScopeAugmentation(node) ? "__global" : `"${(node.name).text}"`; + return isGlobalScopeAugmentation(node) ? "__global" : `"${(name).text}"`; } - if (node.name.kind === SyntaxKind.ComputedPropertyName) { - const nameExpression = (node.name).expression; + if (name.kind === SyntaxKind.ComputedPropertyName) { + const nameExpression = (name).expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; @@ -241,7 +242,7 @@ namespace ts { Debug.assert(isWellKnownSymbolSyntactically(nameExpression)); return getPropertyNameForKnownSymbolName((nameExpression).name.text); } - return (node.name).text; + return (name).text; } switch (node.kind) { case SyntaxKind.Constructor: @@ -259,18 +260,9 @@ namespace ts { case SyntaxKind.ExportAssignment: return (node).isExportEquals ? "export=" : "default"; case SyntaxKind.BinaryExpression: - switch (getSpecialPropertyAssignmentKind(node as BinaryExpression)) { - case SpecialPropertyAssignmentKind.ModuleExports: - // module.exports = ... - return "export="; - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.Property: - // exports.x = ... or this.y = ... - return ((node as BinaryExpression).left as PropertyAccessExpression).name.text; - case SpecialPropertyAssignmentKind.PrototypeProperty: - // className.prototype.methodName = ... - return (((node as BinaryExpression).left as PropertyAccessExpression).expression as PropertyAccessExpression).name.text; + if (getSpecialPropertyAssignmentKind(node as BinaryExpression) === SpecialPropertyAssignmentKind.ModuleExports) { + // module.exports = ... + return "export="; } Debug.fail("Unknown binary declaration kind"); break; @@ -303,7 +295,7 @@ namespace ts { } function getDisplayName(node: Declaration): string { - return node.name ? declarationNameToString(node.name) : getDeclarationName(node); + return (node as NamedDeclaration).name ? declarationNameToString((node as NamedDeclaration).name) : getDeclarationName(node); } /** @@ -366,8 +358,8 @@ namespace ts { symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name)); } else { - if (node.name) { - node.name.parent = node; + if ((node as NamedDeclaration).name) { + (node as NamedDeclaration).name.parent = node; } // Report errors every position with duplicate declaration @@ -389,16 +381,16 @@ namespace ts { // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (isDefaultExport || (node.kind === SyntaxKind.ExportAssignment && !(node).isExportEquals))) { - message = Diagnostics.A_module_cannot_have_multiple_default_exports; - } + (isDefaultExport || (node.kind === SyntaxKind.ExportAssignment && !(node).isExportEquals))) { + message = Diagnostics.A_module_cannot_have_multiple_default_exports; + } } } forEach(symbol.declarations, declaration => { - file.bindDiagnostics.push(createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration))); + file.bindDiagnostics.push(createDiagnosticForNode(getNameOfDeclaration(declaration) || declaration, message, getDisplayName(declaration))); }); - file.bindDiagnostics.push(createDiagnosticForNode(node.name || node, message, getDisplayName(node))); + file.bindDiagnostics.push(createDiagnosticForNode(getNameOfDeclaration(node) || node, message, getDisplayName(node))); symbol = createSymbol(SymbolFlags.None, name); } @@ -438,10 +430,11 @@ namespace ts { // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (node.kind === SyntaxKind.JSDocTypedefTag) Debug.assert(isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. const isJSDocTypedefInJSDocNamespace = node.kind === SyntaxKind.JSDocTypedefTag && - node.name && - node.name.kind === SyntaxKind.Identifier && - (node.name).isInJSDocNamespace; + (node as JSDocTypedefTag).name && + (node as JSDocTypedefTag).name.kind === SyntaxKind.Identifier && + ((node as JSDocTypedefTag).name as Identifier).isInJSDocNamespace; if ((!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) || isJSDocTypedefInJSDocNamespace) { const exportKind = (symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) | @@ -602,9 +595,7 @@ namespace ts { // Binding of JsDocComment should be done before the current block scope container changes. // because the scope of JsDocComment should not be affected by whether the current node is a // container or not. - if (isInJavaScriptFile(node) && node.jsDoc) { - forEach(node.jsDoc, bind); - } + forEach(node.jsDoc, bind); if (checkUnreachable(node)) { bindEachChild(node); return; @@ -1414,7 +1405,7 @@ namespace ts { if (isObjectLiteralOrClassExpressionMethod(node)) { return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals | ContainerFlags.IsFunctionLike | ContainerFlags.IsObjectLiteralOrClassExpressionMethod; } - // falls through + // falls through case SyntaxKind.Constructor: case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodSignature: @@ -1716,7 +1707,7 @@ namespace ts { declareModuleMember(node, symbolFlags, symbolExcludes); break; } - // falls through + // falls through default: if (!blockScopeContainer.locals) { blockScopeContainer.locals = createMap(); @@ -1912,9 +1903,7 @@ namespace ts { // Here the current node is "foo", which is a container, but the scope of "MyType" should // not be inside "foo". Therefore we always bind @typedef before bind the parent node, // and skip binding this tag later when binding all the other jsdoc tags. - if (isInJavaScriptFile(node)) { - bindJSDocTypedefTagIfAny(node); - } + bindJSDocTypedefTagIfAny(node); // First we bind declaration nodes to a symbol if possible. We'll both create a symbol // and then potentially add the symbol to an appropriate symbol table. Possible @@ -2002,7 +1991,7 @@ namespace ts { // for typedef type names with namespaces, bind the new jsdoc type symbol here // because it requires all containing namespaces to be in effect, namely the // current "blockScopeContainer" needs to be set to its immediate namespace parent. - if ((node).isInJSDocNamespace) { + if (isInJavaScriptFile(node) && (node).isInJSDocNamespace) { let parentNode = node.parent; while (parentNode && parentNode.kind !== SyntaxKind.JSDocTypedefTag) { parentNode = parentNode.parent; @@ -2010,7 +1999,7 @@ namespace ts { bindBlockScopedDeclaration(parentNode, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); break; } - // falls through + // falls through case SyntaxKind.ThisKeyword: if (currentFlow && (isExpression(node) || parent.kind === SyntaxKind.ShorthandPropertyAssignment)) { node.flowNode = currentFlow; @@ -2072,10 +2061,7 @@ namespace ts { return bindVariableDeclarationOrBindingElement(node); case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: - case SyntaxKind.JSDocRecordMember: - return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property | ((node).questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes); - case SyntaxKind.JSDocPropertyTag: - return bindJSDocProperty(node); + return bindPropertyWorker(node as PropertyDeclaration | PropertySignature); case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); @@ -2120,13 +2106,10 @@ namespace ts { return bindPropertyOrMethodOrAccessor(node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: - case SyntaxKind.JSDocFunctionType: return bindFunctionOrConstructorType(node); case SyntaxKind.TypeLiteral: case SyntaxKind.MappedType: - case SyntaxKind.JSDocTypeLiteral: - case SyntaxKind.JSDocRecordType: - return bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, "__type"); + return bindAnonymousTypeWorker(node as TypeLiteralNode | MappedTypeNode); case SyntaxKind.ObjectLiteralExpression: return bindObjectLiteralExpression(node); case SyntaxKind.FunctionExpression: @@ -2147,11 +2130,6 @@ namespace ts { return bindClassLikeDeclaration(node); case SyntaxKind.InterfaceDeclaration: return bindBlockScopedDeclaration(node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes); - case SyntaxKind.JSDocTypedefTag: - if (!(node).fullName || (node).fullName.kind === SyntaxKind.Identifier) { - return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); - } - break; case SyntaxKind.TypeAliasDeclaration: return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); case SyntaxKind.EnumDeclaration: @@ -2186,12 +2164,44 @@ namespace ts { if (!isFunctionLike(node.parent)) { return; } - // falls through + // falls through case SyntaxKind.ModuleBlock: return updateStrictModeStatementList((node).statements); + + default: + if (isInJavaScriptFile(node)) return bindJSDocWorker(node); } } + function bindJSDocWorker(node: Node) { + switch (node.kind) { + case SyntaxKind.JSDocRecordMember: + return bindPropertyWorker(node as JSDocRecordMember); + case SyntaxKind.JSDocPropertyTag: + return declareSymbolAndAddToSymbolTable(node as JSDocPropertyTag, SymbolFlags.Property, SymbolFlags.PropertyExcludes); + case SyntaxKind.JSDocFunctionType: + return bindFunctionOrConstructorType(node); + case SyntaxKind.JSDocTypeLiteral: + case SyntaxKind.JSDocRecordType: + return bindAnonymousTypeWorker(node as JSDocTypeLiteral | JSDocRecordType); + case SyntaxKind.JSDocTypedefTag: { + const { fullName } = node as JSDocTypedefTag; + if (!fullName || fullName.kind === SyntaxKind.Identifier) { + return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); + } + break; + } + } + } + + function bindPropertyWorker(node: PropertyDeclaration | PropertySignature) { + return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property | (node.questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes); + } + + function bindAnonymousTypeWorker(node: TypeLiteralNode | MappedTypeNode | JSDocTypeLiteral | JSDocRecordType) { + return bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, "__type"); + } + function checkTypePredicate(node: TypePredicateNode) { const { parameterName, type } = node; if (parameterName && parameterName.kind === SyntaxKind.Identifier) { @@ -2211,7 +2221,7 @@ namespace ts { } function bindSourceFileAsExternalModule() { - bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName) }"`); + bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName)}"`); } function bindExportAssignment(node: ExportAssignment | BinaryExpression) { @@ -2504,7 +2514,7 @@ namespace ts { } function bindParameter(node: ParameterDeclaration) { - if (inStrictMode) { + if (inStrictMode && !isInAmbientContext(node)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) checkStrictModeEvalOrArguments(node, node.name); @@ -2526,7 +2536,7 @@ namespace ts { } function bindFunctionDeclaration(node: FunctionDeclaration) { - if (!isDeclarationFile(file) && !isInAmbientContext(node)) { + if (!file.isDeclarationFile && !isInAmbientContext(node)) { if (isAsyncFunction(node)) { emitFlags |= NodeFlags.HasAsyncFunctions; } @@ -2543,7 +2553,7 @@ namespace ts { } function bindFunctionExpression(node: FunctionExpression) { - if (!isDeclarationFile(file) && !isInAmbientContext(node)) { + if (!file.isDeclarationFile && !isInAmbientContext(node)) { if (isAsyncFunction(node)) { emitFlags |= NodeFlags.HasAsyncFunctions; } @@ -2557,10 +2567,8 @@ namespace ts { } function bindPropertyOrMethodOrAccessor(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { - if (!isDeclarationFile(file) && !isInAmbientContext(node)) { - if (isAsyncFunction(node)) { - emitFlags |= NodeFlags.HasAsyncFunctions; - } + if (!file.isDeclarationFile && !isInAmbientContext(node) && isAsyncFunction(node)) { + emitFlags |= NodeFlags.HasAsyncFunctions; } if (currentFlow && isObjectLiteralOrClassExpressionMethod(node)) { @@ -2572,10 +2580,6 @@ namespace ts { : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } - function bindJSDocProperty(node: JSDocPropertyTag) { - return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); - } - // reachability checks function shouldReportErrorOnModuleDeclaration(node: ModuleDeclaration): boolean { @@ -3398,6 +3402,7 @@ namespace ts { case SyntaxKind.IndexedAccessType: case SyntaxKind.MappedType: case SyntaxKind.LiteralType: + case SyntaxKind.NamespaceExportDeclaration: // Types and signatures are TypeScript syntax, and exclude all other facts. transformFlags = TransformFlags.AssertTypeScript; excludeFlags = TransformFlags.TypeExcludes; diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ad743cd8ccd..0da2e311376 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -47,6 +47,7 @@ namespace ts { let typeCount = 0; let symbolCount = 0; + let enumCount = 0; let symbolInstantiationDepth = 0; const emptyArray: any[] = []; @@ -204,14 +205,17 @@ namespace ts { // since we are only interested in declarations of the module itself return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, - getApparentType + getApparentType, + getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol, + getBaseConstraintOfType, }; const tupleTypes: GenericType[] = []; const unionTypes = createMap(); const intersectionTypes = createMap(); - const stringLiteralTypes = createMap(); - const numericLiteralTypes = createMap(); + const literalTypes = createMap(); const indexedAccessTypes = createMap(); const evolvingArrayTypes: EvolvingArrayType[] = []; @@ -309,13 +313,15 @@ namespace ts { let flowLoopCount = 0; let visitedFlowCount = 0; - const emptyStringType = getLiteralTypeForText(TypeFlags.StringLiteral, ""); - const zeroType = getLiteralTypeForText(TypeFlags.NumberLiteral, "0"); + const emptyStringType = getLiteralType(""); + const zeroType = getLiteralType(0); const resolutionTargets: TypeSystemEntity[] = []; const resolutionResults: boolean[] = []; const resolutionPropertyNames: TypeSystemPropertyName[] = []; + let suggestionCount = 0; + const maximumSuggestionCount = 10; const mergedSymbols: Symbol[] = []; const symbolLinks: SymbolLinks[] = []; const nodeLinks: NodeLinks[] = []; @@ -580,16 +586,16 @@ namespace ts { recordMergedSymbol(target, source); } else if (target.flags & SymbolFlags.NamespaceModule) { - error(source.declarations[0].name, Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(getNameOfDeclaration(source.declarations[0]), Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { const message = target.flags & SymbolFlags.BlockScopedVariable || source.flags & SymbolFlags.BlockScopedVariable ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; forEach(source.declarations, node => { - error(node.name ? node.name : node, message, symbolToString(source)); + error(getNameOfDeclaration(node) || node, message, symbolToString(source)); }); forEach(target.declarations, node => { - error(node.name ? node.name : node, message, symbolToString(source)); + error(getNameOfDeclaration(node) || node, message, symbolToString(source)); }); } } @@ -679,10 +685,6 @@ namespace ts { return type.flags & TypeFlags.Object ? (type).objectFlags : 0; } - function getCheckFlags(symbol: Symbol): CheckFlags { - return symbol.flags & SymbolFlags.Transient ? (symbol).checkFlags : 0; - } - function isGlobalSourceFile(node: Node) { return node.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(node); } @@ -732,7 +734,8 @@ namespace ts { const useFile = getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + isInAmbientContext(declaration)) { // nodes are in different files and order cannot be determined return true; } @@ -840,7 +843,25 @@ namespace ts { // Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and // the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with // the given name can be found. - function resolveName(location: Node | undefined, name: string, meaning: SymbolFlags, nameNotFoundMessage: DiagnosticMessage, nameArg: string | Identifier): Symbol { + function resolveName( + location: Node | undefined, + name: string, + meaning: SymbolFlags, + nameNotFoundMessage: DiagnosticMessage, + nameArg: string | Identifier, + suggestedNameNotFoundMessage?: DiagnosticMessage): Symbol { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + + function resolveNameHelper( + location: Node | undefined, + name: string, + meaning: SymbolFlags, + nameNotFoundMessage: DiagnosticMessage, + nameArg: string | Identifier, + lookup: (symbols: SymbolTable, name: string, meaning: SymbolFlags) => Symbol, + suggestedNameNotFoundMessage?: DiagnosticMessage): Symbol { + const originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location let result: Symbol; let lastLocation: Node; let propertyWithInvalidInitializer: Node; @@ -851,7 +872,7 @@ namespace ts { loop: while (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { let useResult = true; if (isFunctionLike(location) && lastLocation && lastLocation !== (location).body) { // symbol lookup restrictions for function-like declarations @@ -929,12 +950,12 @@ namespace ts { } } - if (result = getSymbol(moduleExports, name, meaning & SymbolFlags.ModuleMember)) { + if (result = lookup(moduleExports, name, meaning & SymbolFlags.ModuleMember)) { break loop; } break; case SyntaxKind.EnumDeclaration: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & SymbolFlags.EnumMember)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & SymbolFlags.EnumMember)) { break loop; } break; @@ -949,7 +970,7 @@ namespace ts { if (isClassLike(location.parent) && !(getModifierFlags(location) & ModifierFlags.Static)) { const ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & SymbolFlags.Value)) { + if (lookup(ctor.locals, name, meaning & SymbolFlags.Value)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -959,7 +980,7 @@ namespace ts { case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: case SyntaxKind.InterfaceDeclaration: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & SymbolFlags.Type)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & SymbolFlags.Type)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -995,7 +1016,7 @@ namespace ts { grandparent = location.parent.parent; if (isClassLike(grandparent) || grandparent.kind === SyntaxKind.InterfaceDeclaration) { // A reference to this grandparent's type parameters would be an error - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & SymbolFlags.Type)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & SymbolFlags.Type)) { error(errorLocation, Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -1059,7 +1080,7 @@ namespace ts { } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { @@ -1070,7 +1091,17 @@ namespace ts { !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg)); + let suggestion: string | undefined; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg)); + } } } return undefined; @@ -1204,6 +1235,10 @@ namespace ts { function checkAndReportErrorForUsingTypeAsValue(errorLocation: Node, name: string, meaning: SymbolFlags): boolean { if (meaning & (SymbolFlags.Value & ~SymbolFlags.NamespaceModule)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Type & ~SymbolFlags.Value, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined)); if (symbol && !(symbol.flags & SymbolFlags.NamespaceModule)) { error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -1240,13 +1275,13 @@ namespace ts { if (!isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & SymbolFlags.BlockScopedVariable) { - error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationNameToString(declaration.name)); + error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationNameToString(getNameOfDeclaration(declaration))); } else if (result.flags & SymbolFlags.Class) { - error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationNameToString(declaration.name)); + error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationNameToString(getNameOfDeclaration(declaration))); } - else if (result.flags & SymbolFlags.Enum) { - error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationNameToString(declaration.name)); + else if (result.flags & SymbolFlags.RegularEnum) { + error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationNameToString(getNameOfDeclaration(declaration))); } } } @@ -1265,7 +1300,7 @@ namespace ts { return node; } - return findAncestor(node, n => n.kind === SyntaxKind.ImportDeclaration) as ImportDeclaration; + return findAncestor(node, isImportDeclaration); } } @@ -1607,6 +1642,12 @@ namespace ts { return; } + if (startsWith(moduleReference, "@types/")) { + const diag = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + const withoutAtTypePrefix = removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } + const ambientModule = tryFindAmbientModule(moduleName, /*withAugmentations*/ true); if (ambientModule) { return ambientModule; @@ -1683,10 +1724,9 @@ namespace ts { // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). function resolveESModuleSymbol(moduleSymbol: Symbol, moduleReferenceExpression: Expression, dontResolveAlias: boolean): Symbol { - let symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); + const symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (SymbolFlags.Module | SymbolFlags.Variable))) { error(moduleReferenceExpression, Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -1869,7 +1909,7 @@ namespace ts { } function createTypeofType() { - return getUnionType(convertToArray(typeofEQFacts.keys(), s => getLiteralTypeForText(TypeFlags.StringLiteral, s))); + return getUnionType(convertToArray(typeofEQFacts.keys(), getLiteralType)); } // A reserved member name starts with two underscores, but the third character cannot be an underscore @@ -1993,7 +2033,7 @@ namespace ts { ts.forEach(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) { const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { return [symbolFromSymbolTable]; } @@ -2241,48 +2281,74 @@ namespace ts { } function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { - const writer = getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - let result = writer.string(); - releaseStringWriter(writer); + const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | NodeBuilderFlags.IgnoreErrors | NodeBuilderFlags.WriteTypeParametersInQualifiedName); + Debug.assert(typeNode !== undefined, "should always get typenode?"); + const options = { removeComments: true }; + const writer = createTextWriter(""); + const printer = createPrinter(options, writer); + const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(EmitHint.Unspecified, typeNode, /*sourceFile*/ sourceFile, writer); + const result = writer.getText(); const maxLength = compilerOptions.noErrorTruncation || flags & TypeFormatFlags.NoTruncation ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + + function toNodeBuilderFlags(flags?: TypeFormatFlags): NodeBuilderFlags { + let result = NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & TypeFormatFlags.NoTruncation) { + result |= NodeBuilderFlags.NoTruncation; + } + if (flags & TypeFormatFlags.UseFullyQualifiedType) { + result |= NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & TypeFormatFlags.SuppressAnyReturnType) { + result |= NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & TypeFormatFlags.WriteArrayAsGenericType) { + result |= NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & TypeFormatFlags.WriteTypeArgumentsOfSignature) { + result |= NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + + return result; + } } function createNodeBuilder() { - let context: NodeBuilderContext; - return { typeToTypeNode: (type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => { - context = createNodeBuilderContext(enclosingDeclaration, flags); - const resultingNode = typeToTypeNodeHelper(type); + const context = createNodeBuilderContext(enclosingDeclaration, flags); + const resultingNode = typeToTypeNodeHelper(type, context); const result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: (indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => { - context = createNodeBuilderContext(enclosingDeclaration, flags); - const resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + const context = createNodeBuilderContext(enclosingDeclaration, flags); + const resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); const result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: (signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => { - context = createNodeBuilderContext(enclosingDeclaration, flags); - const resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + const context = createNodeBuilderContext(enclosingDeclaration, flags); + const resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); const result = context.encounteredError ? undefined : resultingNode; return result; } }; interface NodeBuilderContext { - readonly enclosingDeclaration: Node | undefined; - readonly flags: NodeBuilderFlags | undefined; + enclosingDeclaration: Node | undefined; + flags: NodeBuilderFlags | undefined; + + // State encounteredError: boolean; - inObjectTypeLiteral: boolean; - checkAlias: boolean; symbolStack: Symbol[] | undefined; } @@ -2291,16 +2357,16 @@ namespace ts { enclosingDeclaration, flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type: Type): TypeNode { + function typeToTypeNodeHelper(type: Type, context: NodeBuilderContext): TypeNode { + const inTypeAlias = context.flags & NodeBuilderFlags.InTypeAlias; + context.flags &= ~NodeBuilderFlags.InTypeAlias; + if (!type) { context.encounteredError = true; - // TODO(aozgaa): should we return implict any (undefined) or explicit any (keywordtypenode)? return undefined; } @@ -2316,23 +2382,25 @@ namespace ts { if (type.flags & TypeFlags.Boolean) { return createKeywordTypeNode(SyntaxKind.BooleanKeyword); } - if (type.flags & TypeFlags.Enum) { - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & TypeFlags.EnumLiteral && !(type.flags & TypeFlags.Union)) { + const parentSymbol = getParentOfSymbol(type.symbol); + const parentName = symbolToName(parentSymbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false); + const enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + } + if (type.flags & TypeFlags.EnumLike) { + const name = symbolToName(type.symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false); return createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (TypeFlags.StringLiteral)) { - return createLiteralTypeNode((createLiteral((type).text))); + return createLiteralTypeNode(setEmitFlags(createLiteral((type).value), EmitFlags.NoAsciiEscaping)); } if (type.flags & (TypeFlags.NumberLiteral)) { - return createLiteralTypeNode((createNumericLiteral((type).text))); + return createLiteralTypeNode((createLiteral((type).value))); } if (type.flags & TypeFlags.BooleanLiteral) { return (type).intrinsicName === "true" ? createTrue() : createFalse(); } - if (type.flags & TypeFlags.EnumLiteral) { - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - return createTypeReferenceNode(name, /*typeArguments*/ undefined); - } if (type.flags & TypeFlags.Void) { return createKeywordTypeNode(SyntaxKind.VoidKeyword); } @@ -2352,8 +2420,8 @@ namespace ts { return createKeywordTypeNode(SyntaxKind.ObjectKeyword); } if (type.flags & TypeFlags.TypeParameter && (type as TypeParameter).isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -2366,84 +2434,58 @@ namespace ts { Debug.assert(!!(type.flags & TypeFlags.Object)); return typeReferenceToTypeNode(type); } - if (objectFlags & ObjectFlags.ClassOrInterface) { - Debug.assert(!!(type.flags & TypeFlags.Object)); - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - // TODO(aozgaa): handle type arguments. - return createTypeReferenceNode(name, /*typeArguments*/ undefined); - } - if (type.flags & TypeFlags.TypeParameter) { - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & TypeFlags.TypeParameter || objectFlags & ObjectFlags.ClassOrInterface) { + const name = symbolToName(type.symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return createTypeReferenceNode(name, /*typeArguments*/ undefined); } - - if (context.checkAlias && type.aliasSymbol) { - const name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false); - const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, SymbolFlags.Type, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === SymbolAccessibility.Accessible) { + const name = symbolToTypeReferenceName(type.aliasSymbol); + const typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - - if (type.flags & TypeFlags.Union) { - const formattedUnionTypes = formatUnionTypes((type).types); - const unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return createUnionOrIntersectionTypeNode(SyntaxKind.UnionType, unionTypeNodes); + if (type.flags & (TypeFlags.Union | TypeFlags.Intersection)) { + const types = type.flags & TypeFlags.Union ? formatUnionTypes((type).types) : (type).types; + const typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + const unionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode(type.flags & TypeFlags.Union ? SyntaxKind.UnionType : SyntaxKind.IntersectionType, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - - if (type.flags & TypeFlags.Intersection) { - return createUnionOrIntersectionTypeNode(SyntaxKind.IntersectionType, mapToTypeNodeArray((type as UnionType).types)); - } - if (objectFlags & (ObjectFlags.Anonymous | ObjectFlags.Mapped)) { Debug.assert(!!(type.flags & TypeFlags.Object)); // The type is an object literal type. return createAnonymousTypeNode(type); } - if (type.flags & TypeFlags.Index) { const indexedType = (type).type; - const indexTypeNode = typeToTypeNodeHelper(indexedType); + const indexTypeNode = typeToTypeNodeHelper(indexedType, context); return createTypeOperatorNode(indexTypeNode); } if (type.flags & TypeFlags.IndexedAccess) { - const objectTypeNode = typeToTypeNodeHelper((type).objectType); - const indexTypeNode = typeToTypeNodeHelper((type).indexType); + const objectTypeNode = typeToTypeNodeHelper((type).objectType, context); + const indexTypeNode = typeToTypeNodeHelper((type).indexType, context); return createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types: Type[]): TypeNode[] { - const result = []; - for (const type of types) { - const typeNode = typeToTypeNodeHelper(type); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } - function createMappedTypeNodeFromType(type: MappedType) { Debug.assert(!!(type.flags & TypeFlags.Object)); - const typeParameter = getTypeParameterFromMappedType(type); - const typeParameterNode = typeParameterToDeclaration(typeParameter); - - const templateType = getTemplateTypeFromMappedType(type); - const templateTypeNode = typeToTypeNodeHelper(templateType); const readonlyToken = type.declaration && type.declaration.readonlyToken ? createToken(SyntaxKind.ReadonlyKeyword) : undefined; const questionToken = type.declaration && type.declaration.questionToken ? createToken(SyntaxKind.QuestionToken) : undefined; + const typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + const templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); - return createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + const mappedTypeNode = createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return setEmitFlags(mappedTypeNode, EmitFlags.SingleLine); } function createAnonymousTypeNode(type: ObjectType): TypeNode { @@ -2453,14 +2495,14 @@ namespace ts { if (symbol.flags & SymbolFlags.Class && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (SymbolFlags.Enum | SymbolFlags.ValueModule) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, SymbolFlags.Value); } else if (contains(context.symbolStack, symbol)) { // If type is an anonymous type literal in a type alias declaration, use type alias name const typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - const entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false); + const entityName = symbolToName(typeAlias, context, SymbolFlags.Type, /*expectsIdentifier*/ false); return createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -2508,45 +2550,61 @@ namespace ts { const resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return createTypeLiteralNode(/*members*/ undefined); + return setEmitFlags(createTypeLiteralNode(/*members*/ undefined), EmitFlags.SingleLine); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { const signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType); + const signatureNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType, context); + return signatureNode; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { const signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructorType); + const signatureNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructorType, context); + return signatureNode; } } - const saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + const savedFlags = context.flags; + context.flags |= NodeBuilderFlags.InObjectTypeLiteral; const members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return createTypeLiteralNode(members); + context.flags = savedFlags; + const typeLiteralNode = createTypeLiteralNode(members); + return setEmitFlags(typeLiteralNode, EmitFlags.SingleLine); } - function createTypeQueryNodeFromSymbol(symbol: Symbol) { - const entityName = symbolToName(symbol, /*expectsIdentifier*/ false); + function createTypeQueryNodeFromSymbol(symbol: Symbol, symbolFlags: SymbolFlags) { + const entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); return createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol: Symbol) { + // Unnamed function expressions and arrow functions have reserved names that we don't want to display + const entityName = symbol.flags & SymbolFlags.Class || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false) : createIdentifier(""); + return entityName; + } + function typeReferenceToTypeNode(type: TypeReference) { const typeArguments: Type[] = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - const elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & NodeBuilderFlags.WriteArrayAsGenericType) { + const typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return createTypeReferenceNode("Array", [typeArgumentNode]); + } + + const elementType = typeToTypeNodeHelper(typeArguments[0], context); return createArrayTypeNode(elementType); } else if (type.target.objectFlags & ObjectFlags.Tuple) { if (typeArguments.length > 0) { - const tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + const tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -2554,7 +2612,7 @@ namespace ts { else { const outerTypeParameters = type.target.outerTypeParameters; let i = 0; - let qualifiedName: QualifiedName | undefined = undefined; + let qualifiedName: QualifiedName | undefined; if (outerTypeParameters) { const length = outerTypeParameters.length; while (i < length) { @@ -2567,47 +2625,80 @@ namespace ts { // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!rangeEquals(outerTypeParameters, typeArguments, start, i)) { - const qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true); - if (!qualifiedName) { - qualifiedName = createQualifiedName(qualifiedNamePart, /*right*/ undefined); + const typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + const typeArgumentNodes = typeArgumentSlice && createNodeArray(typeArgumentSlice); + const namePart = symbolToTypeReferenceName(parent); + (namePart.kind === SyntaxKind.Identifier ? namePart : namePart.right).typeArguments = typeArgumentNodes; + + if (qualifiedName) { + Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = createQualifiedName(qualifiedName, /*right*/ undefined); } else { - Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = createQualifiedName(qualifiedName, /*right*/ undefined); + qualifiedName = createQualifiedName(namePart, /*right*/ undefined); } } } } + let entityName: EntityName = undefined; - const nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true); + const nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - const typeParameterCount = (type.target.typeParameters || emptyArray).length; - const typeArgumentNodes = some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + + let typeArgumentNodes: TypeNode[] | undefined; + if (typeArguments.length > 0) { + const typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + + if (typeArgumentNodes) { + const lastIdentifier = entityName.kind === SyntaxKind.Identifier ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } + return createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left: QualifiedName, right: Identifier | QualifiedName) { + Debug.assert(left.right === undefined); + + if (right.kind === SyntaxKind.Identifier) { + left.right = right; + return left; + } + + let rightPart = right; + while (rightPart.left.kind !== SyntaxKind.Identifier) { + rightPart = rightPart.left; + } + + left.right = rightPart.left; + rightPart.left = left; + return right; + } + function createTypeNodesFromResolvedType(resolvedType: ResolvedType): TypeElement[] { const typeElements: TypeElement[] = []; for (const signature of resolvedType.callSignatures) { - typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.CallSignature)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.CallSignature, context)); } for (const signature of resolvedType.constructSignatures) { - typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructSignature)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructSignature, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, IndexKind.String)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, IndexKind.String, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, IndexKind.Number)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, IndexKind.Number, context)); } const properties = resolvedType.properties; @@ -2617,39 +2708,55 @@ namespace ts { for (const propertySymbol of properties) { const propertyType = getTypeOfSymbol(propertySymbol); - const oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0] as TypeElement; - if (!oldDeclaration) { - return; - } - const propertyName = oldDeclaration.name; + const saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + const propertyName = symbolToName(propertySymbol, context, SymbolFlags.Value, /*expectsIdentifier*/ true); + context.enclosingDeclaration = saveEnclosingDeclaration; const optionalToken = propertySymbol.flags & SymbolFlags.Optional ? createToken(SyntaxKind.QuestionToken) : undefined; if (propertySymbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(propertyType).length) { const signatures = getSignaturesOfType(propertyType, SignatureKind.Call); for (const signature of signatures) { - const methodDeclaration = signatureToSignatureDeclarationHelper(signature, SyntaxKind.MethodSignature); + const methodDeclaration = signatureToSignatureDeclarationHelper(signature, SyntaxKind.MethodSignature, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { + const propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : createKeywordTypeNode(SyntaxKind.AnyKeyword); - // TODO(aozgaa): should we create a node with explicit or implict any? - const propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : createKeywordTypeNode(SyntaxKind.AnyKeyword); - typeElements.push(createPropertySignature( + const modifiers = isReadonlySymbol(propertySymbol) ? [createToken(SyntaxKind.ReadonlyKeyword)] : undefined; + const propertySignature = createPropertySignature( + modifiers, propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined)); + /*initializer*/ undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo: IndexInfo, kind: IndexKind): IndexSignatureDeclaration { + function mapToTypeNodes(types: Type[], context: NodeBuilderContext): TypeNode[] { + if (some(types)) { + const result = []; + for (let i = 0; i < types.length; ++i) { + const type = types[i]; + const typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + + return result; + } + } + + function indexInfoToIndexSignatureDeclarationHelper(indexInfo: IndexInfo, kind: IndexKind, context: NodeBuilderContext): IndexSignatureDeclaration { + const name = getNameFromIndexInfo(indexInfo) || "x"; const indexerTypeNode = createKeywordTypeNode(kind === IndexKind.String ? SyntaxKind.StringKeyword : SyntaxKind.NumberKeyword); - const name = getNameFromIndexInfo(indexInfo); const indexingParameter = createParameter( /*decorators*/ undefined, @@ -2659,69 +2766,103 @@ namespace ts { /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - const typeNode = typeToTypeNodeHelper(indexInfo.type); - return createIndexSignatureDeclaration( + const typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [createToken(SyntaxKind.ReadonlyKeyword)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature: Signature, kind: SyntaxKind): SignatureDeclaration { - - const typeParameters = signature.typeParameters && signature.typeParameters.map(parameter => typeParameterToDeclaration(parameter)); - const parameters = signature.parameters.map(parameter => symbolToParameterDeclaration(parameter)); - let returnTypeNode: TypeNode | TypePredicate; + function signatureToSignatureDeclarationHelper(signature: Signature, kind: SyntaxKind, context: NodeBuilderContext): SignatureDeclaration { + const typeParameters = signature.typeParameters && signature.typeParameters.map(parameter => typeParameterToDeclaration(parameter, context)); + const parameters = signature.parameters.map(parameter => symbolToParameterDeclaration(parameter, context)); + if (signature.thisParameter) { + const thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } + let returnTypeNode: TypeNode; if (signature.typePredicate) { const typePredicate = signature.typePredicate; - const parameterName = typePredicate.kind === TypePredicateKind.Identifier ? createIdentifier((typePredicate).parameterName) : createThisTypeNode(); - const typeNode = typeToTypeNodeHelper(typePredicate.type); + const parameterName = typePredicate.kind === TypePredicateKind.Identifier ? + setEmitFlags(createIdentifier((typePredicate).parameterName), EmitFlags.NoAsciiEscaping) : + createThisTypeNode(); + const typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = createTypePredicateNode(parameterName, typeNode); } else { const returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - const returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== SyntaxKind.AnyKeyword ? returnTypeNode : undefined; - - return createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === SyntaxKind.AnyKeyword) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = createKeywordTypeNode(SyntaxKind.AnyKeyword); + } + return createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type: TypeParameter): TypeParameterDeclaration { + function typeParameterToDeclaration(type: TypeParameter, context: NodeBuilderContext): TypeParameterDeclaration { + const name = symbolToName(type.symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ true); const constraint = getConstraintFromTypeParameter(type); - const constraintNode = constraint && typeToTypeNodeHelper(constraint); + const constraintNode = constraint && typeToTypeNodeHelper(constraint, context); const defaultParameter = getDefaultFromTypeParameter(type); - const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - const name = symbolToName(type.symbol, /*expectsIdentifier*/ true); + const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol: Symbol): ParameterDeclaration { - const parameterDeclaration = getDeclarationOfKind(parameterSymbol, SyntaxKind.Parameter); - const parameterType = getTypeOfSymbol(parameterSymbol); - const parameterTypeNode = typeToTypeNodeHelper(parameterType); - // TODO(aozgaa): In the future, check initializer accessibility. + function symbolToParameterDeclaration(parameterSymbol: Symbol, context: NodeBuilderContext): ParameterDeclaration { + const parameterDeclaration = getDeclarationOfKind(parameterSymbol, SyntaxKind.Parameter); + const modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(getSynthesizedClone); + const dotDotDotToken = isRestParameter(parameterDeclaration) ? createToken(SyntaxKind.DotDotDotToken) : undefined; + const name = parameterDeclaration.name ? + parameterDeclaration.name.kind === SyntaxKind.Identifier ? + setEmitFlags(getSynthesizedClone(parameterDeclaration.name), EmitFlags.NoAsciiEscaping) : + cloneBindingName(parameterDeclaration.name) : + parameterSymbol.name; + const questionToken = isOptionalParameter(parameterDeclaration) ? createToken(SyntaxKind.QuestionToken) : undefined; + + let parameterType = getTypeOfSymbol(parameterSymbol); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, TypeFlags.Undefined); + } + const parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + const parameterNode = createParameter( - parameterDeclaration.decorators, - parameterDeclaration.modifiers, - parameterDeclaration.dotDotDotToken && createToken(SyntaxKind.DotDotDotToken), - // Clone name to remove trivia. - getSynthesizedClone(parameterDeclaration.name), - parameterDeclaration.questionToken && createToken(SyntaxKind.QuestionToken), + /*decorators*/ undefined, + modifiers, + dotDotDotToken, + name, + questionToken, parameterTypeNode, - parameterDeclaration.initializer); + /*initializer*/ undefined); return parameterNode; + + function cloneBindingName(node: BindingName): BindingName { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node: Node): Node { + const visited = visitEachChild(node, elideInitializerAndSetEmitFlags, nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + const clone = nodeIsSynthesized(visited) ? visited : getSynthesizedClone(visited); + if (clone.kind === SyntaxKind.BindingElement) { + (clone).initializer = undefined; + } + return setEmitFlags(clone, EmitFlags.SingleLine | EmitFlags.NoAsciiEscaping); + } + } } - function symbolToName(symbol: Symbol, expectsIdentifier: true): Identifier; - function symbolToName(symbol: Symbol, expectsIdentifier: false): EntityName; - function symbolToName(symbol: Symbol, expectsIdentifier: boolean): EntityName { + function symbolToName(symbol: Symbol, context: NodeBuilderContext, meaning: SymbolFlags, expectsIdentifier: true): Identifier; + function symbolToName(symbol: Symbol, context: NodeBuilderContext, meaning: SymbolFlags, expectsIdentifier: false): EntityName; + function symbolToName(symbol: Symbol, context: NodeBuilderContext, meaning: SymbolFlags, expectsIdentifier: boolean): EntityName { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. let chain: Symbol[]; const isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, SymbolFlags.None, /*endOfChain*/ true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); Debug.assert(chain && chain.length > 0); } else { @@ -2730,18 +2871,16 @@ namespace ts { if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain: Symbol[], index: number): EntityName { Debug.assert(chain && 0 <= index && index < chain.length); - // const parentIndex = index - 1; const symbol = chain[index]; - let typeParameterString = ""; - if (index > 0) { - + let typeParameterNodes: TypeNode[] | undefined; + if (context.flags & NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { const parentSymbol = chain[index - 1]; let typeParameters: TypeParameter[]; if (getCheckFlags(symbol) & CheckFlags.Instantiated) { @@ -2753,21 +2892,12 @@ namespace ts { typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - const writer = getSingleLineStringWriter(); - const displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - const symbolName = getNameOfSymbol(symbol); - const symbolNameWithTypeParameters = typeParameterString.length > 0 ? `${symbolName}<${typeParameterString}>` : symbolName; - const identifier = createIdentifier(symbolNameWithTypeParameters); + + const symbolName = getNameOfSymbol(symbol, context); + const identifier = setEmitFlags(createIdentifier(symbolName, typeParameterNodes), EmitFlags.NoAsciiEscaping); return index > 0 ? createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } @@ -2805,29 +2935,30 @@ namespace ts { return [symbol]; } } + } - function getNameOfSymbol(symbol: Symbol): string { - const declaration = firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { - return declarationNameToString((declaration.parent).name); - } - if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case SyntaxKind.ClassExpression: - return "(Anonymous class)"; - case SyntaxKind.FunctionExpression: - case SyntaxKind.ArrowFunction: - return "(Anonymous function)"; - } + function getNameOfSymbol(symbol: Symbol, context: NodeBuilderContext): string { + const declaration = firstOrUndefined(symbol.declarations); + if (declaration) { + const name = getNameOfDeclaration(declaration); + if (name) { + return declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { + return declarationNameToString((declaration.parent).name); + } + if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case SyntaxKind.ClassExpression: + return "(Anonymous class)"; + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } @@ -2848,12 +2979,14 @@ namespace ts { flags |= t.flags; if (!(t.flags & TypeFlags.Nullable)) { if (t.flags & (TypeFlags.BooleanLiteral | TypeFlags.EnumLiteral)) { - const baseType = t.flags & TypeFlags.BooleanLiteral ? booleanType : (t).baseType; - const count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + const baseType = t.flags & TypeFlags.BooleanLiteral ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & TypeFlags.Union) { + const count = (baseType).types.length; + if (i + count <= types.length && types[i + count - 1] === (baseType).types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -2891,14 +3024,15 @@ namespace ts { } function literalTypeToString(type: LiteralType) { - return type.flags & TypeFlags.StringLiteral ? `"${escapeString((type).text)}"` : (type).text; + return type.flags & TypeFlags.StringLiteral ? `"${escapeString((type).value)}"` : "" + (type).value; } function getNameOfSymbol(symbol: Symbol): string { if (symbol.declarations && symbol.declarations.length) { const declaration = symbol.declarations[0]; - if (declaration.name) { - return declarationNameToString(declaration.name); + const name = getNameOfDeclaration(declaration); + if (name) { + return declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { return declarationNameToString((declaration.parent).name); @@ -2961,8 +3095,8 @@ namespace ts { // Write type arguments of instantiated class/interface here if (flags & SymbolFormatFlags.WriteTypeParametersOrArguments) { if (getCheckFlags(symbol) & CheckFlags.Instantiated) { - buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), - (symbol).mapper, writer, enclosingDeclaration); + const params = getTypeParametersOfClassOrInterface(parentSymbol.flags & SymbolFlags.Alias ? resolveAlias(parentSymbol) : parentSymbol); + buildDisplayForTypeArgumentsAndDelimiters(params, (symbol).mapper, writer, enclosingDeclaration); } else { buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); @@ -3029,7 +3163,7 @@ namespace ts { } function buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]) { - const globalFlagsToPass = globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike; + const globalFlagsToPass = globalFlags & (TypeFormatFlags.WriteOwnNameForAnyLike | TypeFormatFlags.WriteClassExpressionAsTypeLiteral); let inObjectTypeLiteral = false; return writeType(type, globalFlags); @@ -3051,12 +3185,17 @@ namespace ts { else if (getObjectFlags(type) & ObjectFlags.Reference) { writeTypeReference(type, nextFlags); } - else if (type.flags & TypeFlags.EnumLiteral) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, nextFlags); - writePunctuation(writer, SyntaxKind.DotToken); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & TypeFlags.EnumLiteral && !(type.flags & TypeFlags.Union)) { + const parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, nextFlags); + // In a literal enum type with a single member E { A }, E and E.A denote the + // same type. We always display this type simply as E. + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, SyntaxKind.DotToken); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & ObjectFlags.ClassOrInterface || type.flags & (TypeFlags.Enum | TypeFlags.TypeParameter)) { + else if (getObjectFlags(type) & ObjectFlags.ClassOrInterface || type.flags & (TypeFlags.EnumLike | TypeFlags.TypeParameter)) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, nextFlags); } @@ -3141,6 +3280,11 @@ namespace ts { writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), SyntaxKind.CommaToken); writePunctuation(writer, SyntaxKind.CloseBracketToken); } + else if (flags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === SyntaxKind.ClassExpression) { + writeAnonymousType(getDeclaredTypeOfClassOrInterface(type.symbol), flags); + } else { // Write the type reference in the format f.g.C where A and B are type arguments // for outer type parameters, and f and g are the respective declaring containers of those @@ -3188,7 +3332,9 @@ namespace ts { const symbol = type.symbol; if (symbol) { // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & SymbolFlags.Class && !getBaseTypeVariableOfClass(symbol) || + if (symbol.flags & SymbolFlags.Class && + !getBaseTypeVariableOfClass(symbol) && + !(symbol.valueDeclaration.kind === SyntaxKind.ClassExpression && flags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral) || symbol.flags & (SymbolFlags.Enum | SymbolFlags.ValueModule)) { writeTypeOfSymbol(type, flags); } @@ -3210,12 +3356,23 @@ namespace ts { else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type + // However, in case of class expressions, we want to write both the static side and the instance side. + // We skip adding the static side so that the instance side has a chance to be written + // before checking for circular references. if (!symbolStack) { symbolStack = []; } - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); + const isConstructorObject = type.flags & TypeFlags.Object && + getObjectFlags(type) & ObjectFlags.Anonymous && + type.symbol && type.symbol.flags & SymbolFlags.Class; + if (isConstructorObject) { + writeLiteralType(type, flags); + } + else { + symbolStack.push(symbol); + writeLiteralType(type, flags); + symbolStack.pop(); + } } } else { @@ -3334,6 +3491,14 @@ namespace ts { buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, IndexKind.String, enclosingDeclaration, globalFlags, symbolStack); buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, IndexKind.Number, enclosingDeclaration, globalFlags, symbolStack); for (const p of resolved.properties) { + if (globalFlags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral) { + if (p.flags & SymbolFlags.Prototype) { + continue; + } + if (getDeclarationModifierFlagsFromSymbol(p) & (ModifierFlags.Private | ModifierFlags.Protected)) { + writer.reportPrivateInBaseOfClassExpression(p.name); + } + } const t = getTypeOfSymbol(p); if (p.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(t).length) { const signatures = getSignaturesOfType(t, SignatureKind.Call); @@ -3348,7 +3513,7 @@ namespace ts { writePropertyWithModifiers(p); writePunctuation(writer, SyntaxKind.ColonToken); writeSpace(writer); - writeType(t, TypeFormatFlags.None); + writeType(t, globalFlags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral); writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } @@ -3427,7 +3592,7 @@ namespace ts { let type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, TypeFlags.Undefined); + type = getNullableType(type, TypeFlags.Undefined); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -3635,8 +3800,8 @@ namespace ts { case SyntaxKind.BindingElement: return isDeclarationVisible(node.parent.parent); case SyntaxKind.VariableDeclaration: - if (isBindingPattern(node.name) && - !(node.name).elements.length) { + if (isBindingPattern((node as VariableDeclaration).name) && + !((node as VariableDeclaration).name as BindingPattern).elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } @@ -4003,7 +4168,7 @@ namespace ts { } function addOptionality(type: Type, optional: boolean): Type { - return strictNullChecks && optional ? includeFalsyTypes(type, TypeFlags.Undefined) : type; + return strictNullChecks && optional ? getNullableType(type, TypeFlags.Undefined) : type; } // Return the inferred type for a variable, parameter, or property declaration @@ -4064,7 +4229,7 @@ namespace ts { const func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present if (func.kind === SyntaxKind.SetAccessor && !hasDynamicName(func)) { - const getter = getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor); + const getter = getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor); if (getter) { const getterSignature = getSignatureFromDeclaration(getter); const thisParameter = getAccessorThisParameter(func as AccessorDeclaration); @@ -4119,6 +4284,7 @@ namespace ts { const types: Type[] = []; let definedInConstructor = false; let definedInMethod = false; + let jsDocType: Type; for (const declaration of symbol.declarations) { const expression = declaration.kind === SyntaxKind.BinaryExpression ? declaration : declaration.kind === SyntaxKind.PropertyAccessExpression ? getAncestor(declaration, SyntaxKind.BinaryExpression) : @@ -4137,19 +4303,26 @@ namespace ts { } } - if (expression.flags & NodeFlags.JavaScriptFile) { - // If there is a JSDoc type, use it - const type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + // If there is a JSDoc type, use it + const type = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type) { + const declarationType = getWidenedType(type); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + const name = getNameOfDeclaration(declaration); + error(name, Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + // If we don't have an explicit JSDoc type, get the type from the expression. + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, /*subtypeReduction*/ true), definedInMethod && !definedInConstructor)); + const type = jsDocType || getUnionType(types, /*subtypeReduction*/ true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if @@ -4345,8 +4518,8 @@ namespace ts { function getTypeOfAccessors(symbol: Symbol): Type { const links = getSymbolLinks(symbol); if (!links.type) { - const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); - const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); + const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); if (getter && getter.flags & NodeFlags.JavaScriptFile) { const jsDocType = getTypeForDeclarationFromJSDocComment(getter); @@ -4395,7 +4568,7 @@ namespace ts { if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); error(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -4422,7 +4595,7 @@ namespace ts { links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & SymbolFlags.Optional ? includeFalsyTypes(type, TypeFlags.Undefined) : type; + links.type = strictNullChecks && symbol.flags & SymbolFlags.Optional ? getNullableType(type, TypeFlags.Undefined) : type; } } } @@ -4707,6 +4880,7 @@ namespace ts { return; } const baseTypeNode = getBaseTypeNodeOfClass(type); + const typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); let baseType: Type; const originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & SymbolFlags.Class && @@ -4714,7 +4888,7 @@ namespace ts { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the // class and all return the instance type of the class. There is no need for further checks and we can apply the // type arguments in the same manner as a type reference to get the same error reporting experience. - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & TypeFlags.Any) { baseType = baseConstructorType; @@ -4872,7 +5046,7 @@ namespace ts { return unknownType; } - let declaration: JSDocTypedefTag | TypeAliasDeclaration = getDeclarationOfKind(symbol, SyntaxKind.JSDocTypedefTag); + let declaration: JSDocTypedefTag | TypeAliasDeclaration = getDeclarationOfKind(symbol, SyntaxKind.JSDocTypedefTag); let type: Type; if (declaration) { if (declaration.jsDocTypeLiteral) { @@ -4883,7 +5057,7 @@ namespace ts { } } else { - declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); + declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); type = getTypeFromTypeNode(declaration.type); } @@ -4906,77 +5080,80 @@ namespace ts { return links.declaredType; } - function isLiteralEnumMember(symbol: Symbol, member: EnumMember) { + function isLiteralEnumMember(member: EnumMember) { const expr = member.initializer; if (!expr) { return !isInAmbientContext(member); } - return expr.kind === SyntaxKind.NumericLiteral || + return expr.kind === SyntaxKind.StringLiteral || expr.kind === SyntaxKind.NumericLiteral || expr.kind === SyntaxKind.PrefixUnaryExpression && (expr).operator === SyntaxKind.MinusToken && (expr).operand.kind === SyntaxKind.NumericLiteral || - expr.kind === SyntaxKind.Identifier && !!symbol.exports.get((expr).text); + expr.kind === SyntaxKind.Identifier && (nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get((expr).text)); } - function enumHasLiteralMembers(symbol: Symbol) { + function getEnumKind(symbol: Symbol): EnumKind { + const links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + let hasNonLiteralMember = false; for (const declaration of symbol.declarations) { if (declaration.kind === SyntaxKind.EnumDeclaration) { for (const member of (declaration).members) { - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === SyntaxKind.StringLiteral) { + return links.enumKind = EnumKind.Literal; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? EnumKind.Numeric : EnumKind.Literal; } - function createEnumLiteralType(symbol: Symbol, baseType: EnumType, text: string) { - const type = createType(TypeFlags.EnumLiteral); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type: Type) { + return type.flags & TypeFlags.EnumLiteral && !(type.flags & TypeFlags.Union) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol: Symbol): Type { const links = getSymbolLinks(symbol); - if (!links.declaredType) { - const enumType = links.declaredType = createType(TypeFlags.Enum); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - const memberTypeList: Type[] = []; - const memberTypes: EnumLiteralType[] = []; - for (const declaration of enumType.symbol.declarations) { - if (declaration.kind === SyntaxKind.EnumDeclaration) { - computeEnumMemberValues(declaration); - for (const member of (declaration).members) { - const memberSymbol = getSymbolOfNode(member); - const value = getEnumMemberValue(member); - if (!memberTypes[value]) { - const memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === EnumKind.Literal) { + enumCount++; + const memberTypeList: Type[] = []; + for (const declaration of symbol.declarations) { + if (declaration.kind === SyntaxKind.EnumDeclaration) { + for (const member of (declaration).members) { + const memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= TypeFlags.Union; - (enumType).types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + const enumType = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); + if (enumType.flags & TypeFlags.Union) { + enumType.flags |= TypeFlags.EnumLiteral; + enumType.symbol = symbol; } + return links.declaredType = enumType; } } - return links.declaredType; + const enumType = createType(TypeFlags.Enum); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol: Symbol): Type { const links = getSymbolLinks(symbol); if (!links.declaredType) { - const enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & TypeFlags.Union ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + const enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -5238,7 +5415,7 @@ namespace ts { } const baseTypeNode = getBaseTypeNodeOfClass(classType); const isJavaScript = isInJavaScriptFile(baseTypeNode); - const typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNode); + const typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); const typeArgCount = length(typeArguments); const result: Signature[] = []; for (const baseSig of baseSignatures) { @@ -5507,7 +5684,7 @@ namespace ts { // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (t.flags & TypeFlags.StringLiteral) { - const propName = (t).text; + const propName = (t).value; const modifiersProp = getPropertyOfType(modifiersType, propName); const isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & SymbolFlags.Optional); const prop = createSymbol(SymbolFlags.Property | (isOptional ? SymbolFlags.Optional : 0), propName); @@ -5648,6 +5825,26 @@ namespace ts { getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type: Type): Symbol[] { + if (type.flags & TypeFlags.Union) { + const props = createMap(); + for (const memberType of (type as UnionType).types) { + if (memberType.flags & TypeFlags.Primitive) { + continue; + } + + for (const { name } of getPropertiesOfType(memberType)) { + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type as UnionType, name)); + } + } + } + return arrayFrom(props.values()); + } else { + return getPropertiesOfType(type); + } + } + function getConstraintOfType(type: TypeVariable | UnionOrIntersectionType): Type { return type.flags & TypeFlags.TypeParameter ? getConstraintOfTypeParameter(type) : type.flags & TypeFlags.IndexedAccess ? getConstraintOfIndexedAccess(type) : @@ -5775,11 +5972,11 @@ namespace ts { const t = type.flags & TypeFlags.TypeVariable ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & TypeFlags.Intersection ? getApparentTypeOfIntersectionType(t) : t.flags & TypeFlags.StringLike ? globalStringType : - t.flags & TypeFlags.NumberLike ? globalNumberType : - t.flags & TypeFlags.BooleanLike ? globalBooleanType : - t.flags & TypeFlags.ESSymbol ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= ScriptTarget.ES2015) : - t.flags & TypeFlags.NonPrimitive ? emptyObjectType : - t; + t.flags & TypeFlags.NumberLike ? globalNumberType : + t.flags & TypeFlags.BooleanLike ? globalBooleanType : + t.flags & TypeFlags.ESSymbol ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= ScriptTarget.ES2015) : + t.flags & TypeFlags.NonPrimitive ? emptyObjectType : + t; } function createUnionOrIntersectionProperty(containingType: UnionOrIntersectionType, name: string): Symbol { @@ -5879,7 +6076,7 @@ namespace ts { * @param type a type to look up property from * @param name a name of property to look up in a given type */ - function getPropertyOfType(type: Type, name: string): Symbol { + function getPropertyOfType(type: Type, name: string): Symbol | undefined { type = getApparentType(type); if (type.flags & TypeFlags.Object) { const resolved = resolveStructuredTypeMembers(type); @@ -5917,14 +6114,14 @@ namespace ts { return getSignaturesOfStructuredType(getApparentType(type), kind); } - function getIndexInfoOfStructuredType(type: Type, kind: IndexKind): IndexInfo { + function getIndexInfoOfStructuredType(type: Type, kind: IndexKind): IndexInfo | undefined { if (type.flags & TypeFlags.StructuredType) { const resolved = resolveStructuredTypeMembers(type); return kind === IndexKind.String ? resolved.stringIndexInfo : resolved.numberIndexInfo; } } - function getIndexTypeOfStructuredType(type: Type, kind: IndexKind): Type { + function getIndexTypeOfStructuredType(type: Type, kind: IndexKind): Type | undefined { const info = getIndexInfoOfStructuredType(type, kind); return info && info.type; } @@ -6160,7 +6357,7 @@ namespace ts { !hasDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { const otherKind = declaration.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; - const other = getDeclarationOfKind(declaration.symbol, otherKind); + const other = getDeclarationOfKind(declaration.symbol, otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } @@ -6203,7 +6400,7 @@ namespace ts { // TypeScript 1.0 spec (April 2014): // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. if (declaration.kind === SyntaxKind.GetAccessor && !hasDynamicName(declaration)) { - const setter = getDeclarationOfKind(declaration.symbol, SyntaxKind.SetAccessor); + const setter = getDeclarationOfKind(declaration.symbol, SyntaxKind.SetAccessor); return getAnnotatedAccessorType(setter); } @@ -6234,8 +6431,8 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return (node).name.kind === SyntaxKind.ComputedPropertyName - && traverse((node).name); + return (node).name.kind === SyntaxKind.ComputedPropertyName + && traverse((node).name); default: return !nodeStartsNewLexicalEnvironment(node) && !isPartOfTypeNode(node) && forEachChild(node, traverse); @@ -6315,8 +6512,9 @@ namespace ts { type = anyType; if (noImplicitAny) { const declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(declaration.name)); + const name = getNameOfDeclaration(declaration); + if (name) { + error(name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(name)); } else { error(declaration, Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -6415,7 +6613,7 @@ namespace ts { } function getConstraintDeclaration(type: TypeParameter) { - return (getDeclarationOfKind(type.symbol, SyntaxKind.TypeParameter)).constraint; + return getDeclarationOfKind(type.symbol, SyntaxKind.TypeParameter).constraint; } function getConstraintFromTypeParameter(typeParameter: TypeParameter): Type { @@ -6500,8 +6698,10 @@ namespace ts { return length(type.target.typeParameters); } - // Get type from reference to class or interface - function getTypeFromClassOrInterfaceReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol): Type { + /** + * Get type from type-reference that reference to class or interface + */ + function getTypeFromClassOrInterfaceReference(node: TypeReferenceType, symbol: Symbol, typeArgs: Type[]): Type { const type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); const typeParameters = type.localTypeParameters; if (typeParameters) { @@ -6520,7 +6720,7 @@ namespace ts { // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -6542,10 +6742,12 @@ namespace ts { return instantiation; } - // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include - // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the - // declared type. Instantiations are cached using the type identities of the type arguments as the key. - function getTypeFromTypeAliasReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol): Type { + /** + * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include + * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the + * declared type. Instantiations are cached using the type identities of the type arguments as the key. + */ + function getTypeFromTypeAliasReference(node: TypeReferenceType, symbol: Symbol, typeArguments: Type[]): Type { const type = getDeclaredTypeOfSymbol(symbol); const typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -6561,7 +6763,6 @@ namespace ts { typeParameters.length); return unknownType; } - const typeArguments = map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -6571,8 +6772,10 @@ namespace ts { return type; } - // Get type from reference to named type that cannot be generic (enum or type parameter) - function getTypeFromNonGenericTypeReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol): Type { + /** + * Get type from reference to named type that cannot be generic (enum or type parameter) + */ + function getTypeFromNonGenericTypeReference(node: TypeReferenceType, symbol: Symbol): Type { if (node.typeArguments) { error(node, Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); return unknownType; @@ -6580,7 +6783,7 @@ namespace ts { return getDeclaredTypeOfSymbol(symbol); } - function getTypeReferenceName(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference): EntityNameOrEntityNameExpression | undefined { + function getTypeReferenceName(node: TypeReferenceType): EntityNameOrEntityNameExpression | undefined { switch (node.kind) { case SyntaxKind.TypeReference: return (node).typeName; @@ -6608,17 +6811,19 @@ namespace ts { return resolveEntityName(typeReferenceName, SymbolFlags.Type) || unknownSymbol; } - function getTypeReferenceType(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol) { + function getTypeReferenceType(node: TypeReferenceType, symbol: Symbol) { + const typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. + if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & SymbolFlags.TypeAlias) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & SymbolFlags.Value && node.kind === SyntaxKind.JSDocTypeReference) { @@ -6649,7 +6854,7 @@ namespace ts { case "Object": return anyType; case "Function": - return anyFunctionType; + return globalFunctionType; case "Array": case "array": return !node.typeArguments || !node.typeArguments.length ? createArrayType(anyType) : undefined; @@ -6665,7 +6870,7 @@ namespace ts { return strictNullChecks ? getUnionType([type, nullType]) : type; } - function getTypeFromTypeReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference): Type { + function getTypeFromTypeReference(node: TypeReferenceType): Type { const links = getNodeLinks(node); if (!links.resolvedType) { let symbol: Symbol; @@ -6686,10 +6891,7 @@ namespace ts { ? (node).expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, SymbolFlags.Type) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & SymbolFlags.TypeAlias ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the // type reference in checkTypeReferenceOrExpressionWithTypeArguments. @@ -6699,6 +6901,10 @@ namespace ts { return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node: TypeReferenceType): Type[] { + return map(node.typeArguments, getTypeFromTypeNode); + } + function getTypeFromTypeQueryNode(node: TypeQueryNode): Type { const links = getNodeLinks(node); if (!links.resolvedType) { @@ -7213,7 +7419,7 @@ namespace ts { function getLiteralTypeFromPropertyName(prop: Symbol) { return getDeclarationModifierFlagsFromSymbol(prop) & ModifierFlags.NonPublicAccessibilityModifier || startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(TypeFlags.StringLiteral, unescapeIdentifier(prop.name)); + getLiteralType(unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type: Type) { @@ -7249,8 +7455,8 @@ namespace ts { function getPropertyTypeForIndexType(objectType: Type, indexType: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode, cacheSymbol: boolean) { const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined; - const propName = indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral | TypeFlags.EnumLiteral) ? - (indexType).text : + const propName = indexType.flags & TypeFlags.StringOrNumberLiteral ? + "" + (indexType).value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? getPropertyNameForKnownSymbolName(((accessExpression.argumentExpression).name).text) : undefined; @@ -7298,7 +7504,7 @@ namespace ts { if (accessNode) { const indexNode = accessNode.kind === SyntaxKind.ElementAccessExpression ? (accessNode).argumentExpression : (accessNode).indexType; if (indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) { - error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, (indexType).text, typeToString(objectType)); + error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + (indexType).value, typeToString(objectType)); } else if (indexType.flags & (TypeFlags.String | TypeFlags.Number)) { error(indexNode, Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -7475,11 +7681,11 @@ namespace ts { if (members.has(leftProp.name)) { const rightProp = members.get(leftProp.name); const rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, TypeFlags.Undefined) || rightProp.flags & SymbolFlags.Optional) { + if (rightProp.flags & SymbolFlags.Optional) { const declarations: Declaration[] = concatenate(leftProp.declarations, rightProp.declarations); const flags = SymbolFlags.Property | (leftProp.flags & SymbolFlags.Optional); const result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, TypeFacts.NEUndefined)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -7509,16 +7715,17 @@ namespace ts { return prop.flags & SymbolFlags.Method && find(prop.declarations, decl => isClassLike(decl.parent)); } - function createLiteralType(flags: TypeFlags, text: string) { + function createLiteralType(flags: TypeFlags, value: string | number, symbol: Symbol) { const type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type: Type) { if (type.flags & TypeFlags.StringOrNumberLiteral && !(type.flags & TypeFlags.FreshLiteral)) { if (!(type).freshType) { - const freshType = createLiteralType(type.flags | TypeFlags.FreshLiteral, (type).text); + const freshType = createLiteralType(type.flags | TypeFlags.FreshLiteral, (type).value, (type).symbol); freshType.regularType = type; (type).freshType = freshType; } @@ -7531,11 +7738,17 @@ namespace ts { return type.flags & TypeFlags.StringOrNumberLiteral && type.flags & TypeFlags.FreshLiteral ? (type).regularType : type; } - function getLiteralTypeForText(flags: TypeFlags, text: string) { - const map = flags & TypeFlags.StringLiteral ? stringLiteralTypes : numericLiteralTypes; - let type = map.get(text); + function getLiteralType(value: string | number, enumId?: number, symbol?: Symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. + const qualifier = typeof value === "number" ? "#" : "@"; + const key = enumId ? enumId + qualifier + value : qualifier + value; + let type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + const flags = (typeof value === "number" ? TypeFlags.NumberLiteral : TypeFlags.StringLiteral) | (enumId ? TypeFlags.EnumLiteral : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -8388,29 +8601,27 @@ namespace ts { false; } - function isEnumTypeRelatedTo(source: EnumType, target: EnumType, errorReporter?: ErrorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol: Symbol, targetSymbol: Symbol, errorReporter?: ErrorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - const id = source.id + "," + target.id; + const id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); const relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & SymbolFlags.RegularEnum) || !(target.symbol.flags & SymbolFlags.RegularEnum) || - (source.flags & TypeFlags.Union) !== (target.flags & TypeFlags.Union)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & SymbolFlags.RegularEnum) || !(targetSymbol.flags & SymbolFlags.RegularEnum)) { enumRelation.set(id, false); return false; } - const targetEnumType = getTypeOfSymbol(target.symbol); - for (const property of getPropertiesOfType(getTypeOfSymbol(source.symbol))) { + const targetEnumType = getTypeOfSymbol(targetSymbol); + for (const property of getPropertiesOfType(getTypeOfSymbol(sourceSymbol))) { if (property.flags & SymbolFlags.EnumMember) { const targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & SymbolFlags.EnumMember)) { if (errorReporter) { errorReporter(Diagnostics.Property_0_is_missing_in_type_1, property.name, - typeToString(target, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType)); + typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType)); } enumRelation.set(id, false); return false; @@ -8422,30 +8633,36 @@ namespace ts { } function isSimpleTypeRelatedTo(source: Type, target: Type, relation: Map, errorReporter?: ErrorReporter) { - if (target.flags & TypeFlags.Never) return false; - if (target.flags & TypeFlags.Any || source.flags & TypeFlags.Never) return true; - if (source.flags & TypeFlags.StringLike && target.flags & TypeFlags.String) return true; - if (source.flags & TypeFlags.NumberLike && target.flags & TypeFlags.Number) return true; - if (source.flags & TypeFlags.BooleanLike && target.flags & TypeFlags.Boolean) return true; - if (source.flags & TypeFlags.EnumLiteral && target.flags & TypeFlags.Enum && (source).baseType === target) return true; - if (source.flags & TypeFlags.Enum && target.flags & TypeFlags.Enum && isEnumTypeRelatedTo(source, target, errorReporter)) return true; - if (source.flags & TypeFlags.Undefined && (!strictNullChecks || target.flags & (TypeFlags.Undefined | TypeFlags.Void))) return true; - if (source.flags & TypeFlags.Null && (!strictNullChecks || target.flags & TypeFlags.Null)) return true; - if (source.flags & TypeFlags.Object && target.flags & TypeFlags.NonPrimitive) return true; + const s = source.flags; + const t = target.flags; + if (t & TypeFlags.Never) return false; + if (t & TypeFlags.Any || s & TypeFlags.Never) return true; + if (s & TypeFlags.StringLike && t & TypeFlags.String) return true; + if (s & TypeFlags.StringLiteral && s & TypeFlags.EnumLiteral && + t & TypeFlags.StringLiteral && !(t & TypeFlags.EnumLiteral) && + (source).value === (target).value) return true; + if (s & TypeFlags.NumberLike && t & TypeFlags.Number) return true; + if (s & TypeFlags.NumberLiteral && s & TypeFlags.EnumLiteral && + t & TypeFlags.NumberLiteral && !(t & TypeFlags.EnumLiteral) && + (source).value === (target).value) return true; + if (s & TypeFlags.BooleanLike && t & TypeFlags.Boolean) return true; + if (s & TypeFlags.Enum && t & TypeFlags.Enum && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; + if (s & TypeFlags.EnumLiteral && t & TypeFlags.EnumLiteral) { + if (s & TypeFlags.Union && t & TypeFlags.Union && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; + if (s & TypeFlags.Literal && t & TypeFlags.Literal && + (source).value === (target).value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; + } + if (s & TypeFlags.Undefined && (!strictNullChecks || t & (TypeFlags.Undefined | TypeFlags.Void))) return true; + if (s & TypeFlags.Null && (!strictNullChecks || t & TypeFlags.Null)) return true; + if (s & TypeFlags.Object && t & TypeFlags.NonPrimitive) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & TypeFlags.Any) return true; - if ((source.flags & TypeFlags.Number | source.flags & TypeFlags.NumberLiteral) && target.flags & TypeFlags.EnumLike) return true; - if (source.flags & TypeFlags.EnumLiteral && - target.flags & TypeFlags.EnumLiteral && - (source).text === (target).text && - isEnumTypeRelatedTo((source).baseType, (target).baseType, errorReporter)) { - return true; - } - if (source.flags & TypeFlags.EnumLiteral && - target.flags & TypeFlags.Enum && - isEnumTypeRelatedTo(target, (source).baseType, errorReporter)) { - return true; - } + if (s & TypeFlags.Any) return true; + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (s & (TypeFlags.Number | TypeFlags.NumberLiteral) && !(s & TypeFlags.EnumLiteral) && ( + t & TypeFlags.Enum || t & TypeFlags.NumberLiteral && t & TypeFlags.EnumLiteral)) return true; } return false; } @@ -8694,29 +8911,6 @@ namespace ts { return Ternary.False; } - // Check if a property with the given name is known anywhere in the given type. In an object type, a property - // is considered known if the object type is empty and the check is for assignability, if the object type has - // index signatures, or if the property is actually declared in the object type. In a union or intersection - // type, a property is considered known if it is known in any constituent type. - function isKnownProperty(type: Type, name: string, isComparingJsxAttributes: boolean): boolean { - if (type.flags & TypeFlags.Object) { - const resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. - return true; - } - } - else if (type.flags & TypeFlags.UnionOrIntersection) { - for (const t of (type).types) { - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } - function hasExcessProperties(source: FreshObjectLiteralType, target: Type, reportErrors: boolean): boolean { if (maybeTypeOfKind(target, TypeFlags.Object) && !(getObjectFlags(target) & ObjectFlags.ObjectLiteralPatternWithComputedProperties)) { const isComparingJsxAttributes = !!(source.flags & TypeFlags.JsxAttributes); @@ -9622,7 +9816,7 @@ namespace ts { return getUnionType(types, /*subtypeReduction*/ true); } const supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & TypeFlags.Nullable); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & TypeFlags.Nullable); } function reportNoCommonSupertypeError(types: Type[], errorLocation: Node, errorMessageChainHead: DiagnosticMessageChain): void { @@ -9687,26 +9881,26 @@ namespace ts { function isLiteralType(type: Type): boolean { return type.flags & TypeFlags.Boolean ? true : - type.flags & TypeFlags.Union ? type.flags & TypeFlags.Enum ? true : !forEach((type).types, t => !isUnitType(t)) : - isUnitType(type); + type.flags & TypeFlags.Union ? type.flags & TypeFlags.EnumLiteral ? true : !forEach((type).types, t => !isUnitType(t)) : + isUnitType(type); } function getBaseTypeOfLiteralType(type: Type): Type { - return type.flags & TypeFlags.StringLiteral ? stringType : + return type.flags & TypeFlags.EnumLiteral ? getBaseTypeOfEnumLiteralType(type) : + type.flags & TypeFlags.StringLiteral ? stringType : type.flags & TypeFlags.NumberLiteral ? numberType : - type.flags & TypeFlags.BooleanLiteral ? booleanType : - type.flags & TypeFlags.EnumLiteral ? (type).baseType : - type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(sameMap((type).types, getBaseTypeOfLiteralType)) : - type; + type.flags & TypeFlags.BooleanLiteral ? booleanType : + type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getBaseTypeOfLiteralType)) : + type; } function getWidenedLiteralType(type: Type): Type { - return type.flags & TypeFlags.StringLiteral && type.flags & TypeFlags.FreshLiteral ? stringType : + return type.flags & TypeFlags.EnumLiteral ? getBaseTypeOfEnumLiteralType(type) : + type.flags & TypeFlags.StringLiteral && type.flags & TypeFlags.FreshLiteral ? stringType : type.flags & TypeFlags.NumberLiteral && type.flags & TypeFlags.FreshLiteral ? numberType : - type.flags & TypeFlags.BooleanLiteral ? booleanType : - type.flags & TypeFlags.EnumLiteral ? (type).baseType : - type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(sameMap((type).types, getWidenedLiteralType)) : - type; + type.flags & TypeFlags.BooleanLiteral ? booleanType : + type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getWidenedLiteralType)) : + type; } /** @@ -9730,24 +9924,10 @@ namespace ts { // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type: Type): TypeFlags { return type.flags & TypeFlags.Union ? getFalsyFlagsOfTypes((type).types) : - type.flags & TypeFlags.StringLiteral ? (type).text === "" ? TypeFlags.StringLiteral : 0 : - type.flags & TypeFlags.NumberLiteral ? (type).text === "0" ? TypeFlags.NumberLiteral : 0 : - type.flags & TypeFlags.BooleanLiteral ? type === falseType ? TypeFlags.BooleanLiteral : 0 : - type.flags & TypeFlags.PossiblyFalsy; - } - - function includeFalsyTypes(type: Type, flags: TypeFlags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - const types = [type]; - if (flags & TypeFlags.StringLike) types.push(emptyStringType); - if (flags & TypeFlags.NumberLike) types.push(zeroType); - if (flags & TypeFlags.BooleanLike) types.push(falseType); - if (flags & TypeFlags.Void) types.push(voidType); - if (flags & TypeFlags.Undefined) types.push(undefinedType); - if (flags & TypeFlags.Null) types.push(nullType); - return getUnionType(types); + type.flags & TypeFlags.StringLiteral ? (type).value === "" ? TypeFlags.StringLiteral : 0 : + type.flags & TypeFlags.NumberLiteral ? (type).value === 0 ? TypeFlags.NumberLiteral : 0 : + type.flags & TypeFlags.BooleanLiteral ? type === falseType ? TypeFlags.BooleanLiteral : 0 : + type.flags & TypeFlags.PossiblyFalsy; } function removeDefinitelyFalsyTypes(type: Type): Type { @@ -9756,6 +9936,28 @@ namespace ts { type; } + function extractDefinitelyFalsyTypes(type: Type): Type { + return mapType(type, getDefinitelyFalsyPartOfType); + } + + function getDefinitelyFalsyPartOfType(type: Type): Type { + return type.flags & TypeFlags.String ? emptyStringType : + type.flags & TypeFlags.Number ? zeroType : + type.flags & TypeFlags.Boolean || type === falseType ? falseType : + type.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null) || + type.flags & TypeFlags.StringLiteral && (type).value === "" || + type.flags & TypeFlags.NumberLiteral && (type).value === 0 ? type : + neverType; + } + + function getNullableType(type: Type, flags: TypeFlags): Type { + const missing = (flags & ~type.flags) & (TypeFlags.Undefined | TypeFlags.Null); + return missing === 0 ? type : + missing === TypeFlags.Undefined ? getUnionType([type, undefinedType]) : + missing === TypeFlags.Null ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } + function getNonNullableType(type: Type): Type { return strictNullChecks ? getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull) : type; } @@ -9926,7 +10128,7 @@ namespace ts { case SyntaxKind.SetAccessor: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - if (!declaration.name) { + if (!(declaration as NamedDeclaration).name) { error(declaration, Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } @@ -9935,7 +10137,7 @@ namespace ts { default: diagnostic = Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration: Declaration, type: Type) { @@ -10028,7 +10230,7 @@ namespace ts { const templateType = getTemplateTypeFromMappedType(target); const readonlyMask = target.declaration.readonlyToken ? false : true; const optionalMask = target.declaration.questionToken ? 0 : SymbolFlags.Optional; - const members = createSymbolTable(properties); + const members = createMap(); for (const prop of properties) { const inferredPropType = inferTargetType(getTypeOfSymbol(prop)); if (!inferredPropType) { @@ -10063,22 +10265,11 @@ namespace ts { } function inferTypes(typeVariables: TypeVariable[], typeInferences: TypeInferences[], originalSource: Type, originalTarget: Type) { - let sourceStack: Type[]; - let targetStack: Type[]; - let depth = 0; + let symbolStack: Symbol[]; + let visited: Map; let inferiority = 0; - const visited = createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source: Type, target: Type) { - for (let i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } - function inferFromTypes(source: Type, target: Type) { if (!couldContainTypeVariables(target)) { return; @@ -10093,7 +10284,7 @@ namespace ts { } return; } - if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union && !(source.flags & TypeFlags.Enum && target.flags & TypeFlags.Enum) || + if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union && !(source.flags & TypeFlags.EnumLiteral && target.flags & TypeFlags.EnumLiteral) || source.flags & TypeFlags.Intersection && target.flags & TypeFlags.Intersection) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. @@ -10206,26 +10397,29 @@ namespace ts { else { source = getApparentType(source); if (source.flags & TypeFlags.Object) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } const key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = createMap())).set(key, true); + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + const isNonConstructorObject = target.flags & TypeFlags.Object && + !(getObjectFlags(target) & ObjectFlags.Anonymous && target.symbol && target.symbol.flags & SymbolFlags.Class); + const symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -10428,7 +10622,7 @@ namespace ts { function getResolvedSymbol(node: Identifier): Symbol { const links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !nodeIsMissing(node) && resolveName(node, node.text, SymbolFlags.Value | SymbolFlags.ExportValue, Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !nodeIsMissing(node) && resolveName(node, node.text, SymbolFlags.Value | SymbolFlags.ExportValue, Diagnostics.Cannot_find_name_0, node, Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -10445,11 +10639,13 @@ namespace ts { // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node: Node): string { if (node.kind === SyntaxKind.Identifier) { const symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === SyntaxKind.ThisKeyword) { return "0"; @@ -10611,15 +10807,16 @@ namespace ts { return strictNullChecks ? TypeFacts.StringStrictFacts : TypeFacts.StringFacts; } if (flags & TypeFlags.StringLiteral) { + const isEmpty = (type).value === ""; return strictNullChecks ? - (type).text === "" ? TypeFacts.EmptyStringStrictFacts : TypeFacts.NonEmptyStringStrictFacts : - (type).text === "" ? TypeFacts.EmptyStringFacts : TypeFacts.NonEmptyStringFacts; + isEmpty ? TypeFacts.EmptyStringStrictFacts : TypeFacts.NonEmptyStringStrictFacts : + isEmpty ? TypeFacts.EmptyStringFacts : TypeFacts.NonEmptyStringFacts; } if (flags & (TypeFlags.Number | TypeFlags.Enum)) { return strictNullChecks ? TypeFacts.NumberStrictFacts : TypeFacts.NumberFacts; } - if (flags & (TypeFlags.NumberLiteral | TypeFlags.EnumLiteral)) { - const isZero = (type).text === "0"; + if (flags & TypeFlags.NumberLiteral) { + const isZero = (type).value === 0; return strictNullChecks ? isZero ? TypeFacts.ZeroStrictFacts : TypeFacts.NonZeroStrictFacts : isZero ? TypeFacts.ZeroFacts : TypeFacts.NonZeroFacts; @@ -10851,7 +11048,7 @@ namespace ts { } return true; } - if (source.flags & TypeFlags.EnumLiteral && target.flags & TypeFlags.Enum && (source).baseType === target) { + if (source.flags & TypeFlags.EnumLiteral && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -11714,6 +11911,29 @@ namespace ts { return annotationIncludesUndefined ? getTypeWithFacts(declaredType, TypeFacts.NEUndefined) : declaredType; } + function isApparentTypePosition(node: Node) { + const parent = node.parent; + return parent.kind === SyntaxKind.PropertyAccessExpression || + parent.kind === SyntaxKind.CallExpression && (parent).expression === node || + parent.kind === SyntaxKind.ElementAccessExpression && (parent).expression === node; + } + + function typeHasNullableConstraint(type: Type) { + return type.flags & TypeFlags.TypeVariable && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, TypeFlags.Nullable); + } + + function getDeclaredOrApparentType(symbol: Symbol, node: Node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. + const type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } + function checkIdentifier(node: Identifier): Type { const symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -11789,7 +12009,7 @@ namespace ts { checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - const type = getTypeOfSymbol(localOrExportSymbol); + const type = getDeclaredOrApparentType(localOrExportSymbol, node); const declaration = localOrExportSymbol.valueDeclaration; const assignmentKind = getAssignmentTargetKind(node); @@ -11829,10 +12049,11 @@ namespace ts { // declaration container are the same). const assumeInitialized = isParameter || isOuterVariable || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & TypeFlags.Any) !== 0 || isInTypeQuery(node) || node.parent.kind === SyntaxKind.ExportSpecifier) || + node.parent.kind === SyntaxKind.NonNullExpression || isInAmbientContext(declaration); const initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, getRootDeclaration(declaration) as VariableLikeDeclaration) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, TypeFlags.Undefined); + getNullableType(type, TypeFlags.Undefined); const flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the @@ -11840,7 +12061,7 @@ namespace ts { if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(getNameOfDeclaration(declaration), Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -12508,7 +12729,7 @@ namespace ts { // corresponding set accessor has a type annotation, return statements in the function are contextually typed if (functionDecl.type || functionDecl.kind === SyntaxKind.Constructor || - functionDecl.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(functionDecl.symbol, SyntaxKind.SetAccessor))) { + functionDecl.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(functionDecl.symbol, SyntaxKind.SetAccessor))) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } @@ -12544,7 +12765,7 @@ namespace ts { function getContextualTypeForBinaryOperand(node: Expression): Type { const binaryExpression = node.parent; const operator = binaryExpression.operatorToken.kind; - if (operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment) { + if (isAssignmentOperator(operator)) { // Don't do this for special property assignments to avoid circularity if (getSpecialPropertyAssignmentKind(binaryExpression) !== SpecialPropertyAssignmentKind.None) { return undefined; @@ -12717,7 +12938,7 @@ namespace ts { * @param node the expression whose contextual type will be returned. * @returns the contextual type of an expression. */ - function getContextualType(node: Expression): Type { + function getContextualType(node: Expression): Type | undefined { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; @@ -13166,6 +13387,8 @@ namespace ts { if (spread.flags & TypeFlags.Object) { // only set the symbol and flags if this is a (fresh) object type spread.flags |= propagatedFlags; + spread.flags |= TypeFlags.FreshLiteral; + (spread as ObjectType).objectFlags |= ObjectFlags.ObjectLiteral; spread.symbol = node.symbol; } return spread; @@ -13191,7 +13414,7 @@ namespace ts { } return result; } - } + } function isValidSpreadType(type: Type): boolean { return !!(type.flags & (TypeFlags.Any | TypeFlags.Null | TypeFlags.Undefined | TypeFlags.NonPrimitive) || @@ -13255,6 +13478,9 @@ namespace ts { let spread: Type = emptyObjectType; let attributesArray: Symbol[] = []; let hasSpreadAnyType = false; + let typeToIntersect: Type; + let explicitlySpecifyChildrenAttribute = false; + const jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (const attributeDecl of attributes.properties) { const member = attributeDecl.symbol; @@ -13273,6 +13499,9 @@ namespace ts { attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { Debug.assert(attributeDecl.kind === SyntaxKind.JsxSpreadAttribute); @@ -13282,14 +13511,15 @@ namespace ts { attributesTable = createMap(); } const exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); - hasSpreadAnyType = true; - } if (isTypeAny(exprType)) { hasSpreadAnyType = true; } - spread = getSpreadType(spread, exprType); + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } } } @@ -13297,19 +13527,15 @@ namespace ts { if (spread !== emptyObjectType) { if (attributesArray.length > 0) { spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = createMap(); } attributesArray = getPropertiesOfType(spread); } attributesTable = createMap(); - if (attributesArray) { - forEach(attributesArray, (attr) => { - if (!filter || filter(attr)) { - attributesTable.set(attr.name, attr); - } - }); + for (const attr of attributesArray) { + if (!filter || filter(attr)) { + attributesTable.set(attr.name, attr); + } } } @@ -13331,11 +13557,11 @@ namespace ts { } } - // Error if there is a attribute named "children" and children element. - // This is because children element will overwrite the value from attributes - const jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { error(attributes, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } @@ -13348,7 +13574,13 @@ namespace ts { } } - return hasSpreadAnyType ? anyType : createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + + const attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; /** * Create anonymous type from given attributes symbol table. @@ -13357,8 +13589,7 @@ namespace ts { */ function createJsxAttributesType(symbol: Symbol, attributesTable: Map) { const result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral; - result.flags |= TypeFlags.JsxAttributes | TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag; + result.flags |= TypeFlags.JsxAttributes | TypeFlags.ContainsObjectLiteral; result.objectFlags |= ObjectFlags.ObjectLiteral; return result; } @@ -13515,6 +13746,20 @@ namespace ts { return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType: Type): Type { + if (!propsType) { + return undefined; + } + if (propsType.flags & TypeFlags.Intersection) { + const propsApparentType: Type[] = []; + for (const t of (propsType).types) { + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } + /** * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. * Return only attributes type of successfully resolved call signature. @@ -13535,6 +13780,7 @@ namespace ts { if (callSignature !== unknownSignature) { const callReturnType = callSignature && getReturnTypeOfSignature(callSignature); let paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); @@ -13572,7 +13818,8 @@ namespace ts { let allMatchingAttributesType: Type; for (const candidate of candidatesOutArray) { const callReturnType = getReturnTypeOfSignature(candidate); - const paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + let paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { let shouldBeCandidate = true; for (const attribute of openingLikeElement.attributes.properties) { @@ -13648,7 +13895,7 @@ namespace ts { // Hello World const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - const stringLiteralTypeName = (elementType).text; + const stringLiteralTypeName = (elementType).value; const intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -13877,6 +14124,34 @@ namespace ts { checkJsxAttributesAssignableToTagNameAttributes(node); } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if the object type is empty and the check is for assignability, if the object type has + * index signatures, or if the property is actually declared in the object type. In a union or intersection + * type, a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType: Type, name: string, isComparingJsxAttributes: boolean): boolean { + if (targetType.flags & TypeFlags.Object) { + const resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & TypeFlags.UnionOrIntersection) { + for (const t of (targetType).types) { + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } + /** * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" @@ -13909,7 +14184,19 @@ namespace ts { error(openingLikeElement, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties + const isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (const attribute of openingLikeElement.attributes.properties) { + if (isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, /*isComparingJsxAttributes*/ true)) { + error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; + } + } + } } } @@ -13932,25 +14219,6 @@ namespace ts { return s.valueDeclaration ? s.valueDeclaration.kind : SyntaxKind.PropertyDeclaration; } - function getDeclarationModifierFlagsFromSymbol(s: Symbol): ModifierFlags { - if (s.valueDeclaration) { - const flags = getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & SymbolFlags.Class ? flags : flags & ~ModifierFlags.AccessibilityModifier; - } - if (getCheckFlags(s) & CheckFlags.Synthetic) { - const checkFlags = (s).checkFlags; - const accessModifier = checkFlags & CheckFlags.ContainsPrivate ? ModifierFlags.Private : - checkFlags & CheckFlags.ContainsPublic ? ModifierFlags.Public : - ModifierFlags.Protected; - const staticModifier = checkFlags & CheckFlags.ContainsStatic ? ModifierFlags.Static : 0; - return accessModifier | staticModifier; - } - if (s.flags & SymbolFlags.Prototype) { - return ModifierFlags.Public | ModifierFlags.Static; - } - return 0; - } - function getDeclarationNodeFlagsFromSymbol(s: Symbol): NodeFlags { return s.valueDeclaration ? getCombinedNodeFlags(s.valueDeclaration) : 0; } @@ -14083,44 +14351,6 @@ namespace ts { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode: Identifier, containingType: Type) { - let errorInfo: DiagnosticMessageChain; - if (containingType.flags & TypeFlags.Union && !(containingType.flags & TypeFlags.Primitive)) { - for (const subtype of (containingType as UnionType).types) { - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - - function markPropertyAsReferenced(prop: Symbol) { - if (prop && - noUnusedIdentifiers && - (prop.flags & SymbolFlags.ClassMember) && - prop.valueDeclaration && (getModifierFlags(prop.valueDeclaration) & ModifierFlags.Private)) { - if (getCheckFlags(prop) & CheckFlags.Instantiated) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - - function isInPropertyInitializer(node: Node): boolean { - while (node) { - if (node.parent && node.parent.kind === SyntaxKind.PropertyDeclaration && (node.parent as PropertyDeclaration).initializer === node) { - return true; - } - node = node.parent; - } - return false; - } - function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, right: Identifier) { const type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -14162,7 +14392,7 @@ namespace ts { checkPropertyAccessibility(node, left, apparentType, prop); - const propType = getTypeOfSymbol(prop); + const propType = getDeclaredOrApparentType(prop, node); const assignmentKind = getAssignmentTargetKind(node); if (assignmentKind) { @@ -14184,6 +14414,130 @@ namespace ts { return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode: Identifier, containingType: Type) { + let errorInfo: DiagnosticMessageChain; + if (containingType.flags & TypeFlags.Union && !(containingType.flags & TypeFlags.Primitive)) { + for (const subtype of (containingType as UnionType).types) { + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + const suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + + function getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined { + const suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), SymbolFlags.Value); + return suggestion && suggestion.name; + } + + function getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string { + const result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, (symbols, name, meaning) => { + const symbol = getSymbol(symbols, name, meaning); + if (symbol) { + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol; + } + return getSpellingSuggestionForName(name, arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 0.3 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + * Names longer than 30 characters don't get suggestions because Levenshtein distance is an n**2 algorithm. + */ + function getSpellingSuggestionForName(name: string, symbols: Symbol[], meaning: SymbolFlags): Symbol | undefined { + const worstDistance = name.length * 0.4; + const maximumLengthDifference = Math.min(3, name.length * 0.34); + let bestDistance = Number.MAX_VALUE; + let bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (const candidate of symbols) { + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + const candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + const distance = levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + + function markPropertyAsReferenced(prop: Symbol) { + if (prop && + noUnusedIdentifiers && + (prop.flags & SymbolFlags.ClassMember) && + prop.valueDeclaration && (getModifierFlags(prop.valueDeclaration) & ModifierFlags.Private)) { + if (getCheckFlags(prop) & CheckFlags.Instantiated) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + + function isInPropertyInitializer(node: Node): boolean { + while (node) { + if (node.parent && node.parent.kind === SyntaxKind.PropertyDeclaration && (node.parent as PropertyDeclaration).initializer === node) { + return true; + } + node = node.parent; + } + return false; + } + function isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean { const left = node.kind === SyntaxKind.PropertyAccessExpression ? (node).expression @@ -14324,7 +14678,18 @@ namespace ts { return true; } + function callLikeExpressionMayHaveTypeArguments(node: CallLikeExpression): node is CallExpression | NewExpression { + // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) + return isCallOrNewExpression(node); + } + function resolveUntypedCall(node: CallLikeExpression): Signature { + if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. + forEach(node.typeArguments, checkSourceElement); + } + if (node.kind === SyntaxKind.TaggedTemplateExpression) { checkExpression((node).template); } @@ -14478,7 +14843,7 @@ namespace ts { // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } // Too many arguments implies incorrect arity. @@ -14893,7 +15258,7 @@ namespace ts { case SyntaxKind.Identifier: case SyntaxKind.NumericLiteral: case SyntaxKind.StringLiteral: - return getLiteralTypeForText(TypeFlags.StringLiteral, (element.name).text); + return getLiteralType((element.name).text); case SyntaxKind.ComputedPropertyName: const nameType = checkComputedPropertyName(element.name); @@ -15019,7 +15384,7 @@ namespace ts { } } - function resolveCall(node: CallLikeExpression, signatures: Signature[], candidatesOutArray: Signature[], headMessage?: DiagnosticMessage): Signature { + function resolveCall(node: CallLikeExpression, signatures: Signature[], candidatesOutArray: Signature[], fallbackError?: DiagnosticMessage): Signature { const isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; const isDecorator = node.kind === SyntaxKind.Decorator; const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node); @@ -15054,7 +15419,7 @@ namespace ts { // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(createDiagnosticForNode(node, Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } @@ -15162,7 +15527,7 @@ namespace ts { else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { const typeArguments = (node).typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments, map(typeArguments, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments, map(typeArguments, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); } else { Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -15173,15 +15538,44 @@ namespace ts { Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, (node).tagName || (node).expression || (node).tag, diagnosticChainHead); } } - else { - reportError(Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && every(signatures, sig => length(sig.typeParameters) !== typeArguments.length)) { + let min = Number.POSITIVE_INFINITY; + let max = Number.NEGATIVE_INFINITY; + for (const sig of signatures) { + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, length(sig.typeParameters)); + } + const paramCount = min < max ? `${min}-${max}` : min; + diagnostics.add(createDiagnosticForNode(node, Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + let min = Number.POSITIVE_INFINITY; + let max = Number.NEGATIVE_INFINITY; + for (const sig of signatures) { + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + const hasRestParameter = some(signatures, sig => sig.hasRestParameter); + const hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + const paramCount = hasRestParameter ? min : + min < max ? `${min}-${max}` : + min; + const argCount = args.length - (hasSpreadArgument ? 1 : 0); + const error = hasRestParameter && hasSpreadArgument ? Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter ? Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(createDiagnosticForNode(node, error, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(createDiagnosticForNode(node, fallbackError)); } // No signature was applicable. We have already reported the errors for the invalid signature. @@ -15202,16 +15596,6 @@ namespace ts { return resolveErrorCall(node); - function reportError(message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string): void { - let errorInfo: DiagnosticMessageChain; - errorInfo = chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = chainDiagnosticMessages(errorInfo, headMessage); - } - - diagnostics.add(createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } - function chooseOverload(candidates: Signature[], relation: Map, signatureHelpTrailingComma = false) { for (const originalCandidate of candidates) { if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { @@ -15392,7 +15776,7 @@ namespace ts { // only the class declaration node will have the Abstract flag set. const valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && getModifierFlags(valueDecl) & ModifierFlags.Abstract) { - error(node, Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, declarationNameToString(valueDecl.name)); + error(node, Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, declarationNameToString(getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } @@ -15808,7 +16192,7 @@ namespace ts { if (strictNullChecks) { const declaration = symbol.valueDeclaration; if (declaration && (declaration).initializer) { - return includeFalsyTypes(type, TypeFlags.Undefined); + return getNullableType(type, TypeFlags.Undefined); } } return type; @@ -15878,11 +16262,11 @@ namespace ts { const links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + const name = getNameOfDeclaration(parameter.valueDeclaration); // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === SyntaxKind.ObjectBindingPattern || - parameter.valueDeclaration.name.kind === SyntaxKind.ArrayBindingPattern)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === SyntaxKind.ObjectBindingPattern || name.kind === SyntaxKind.ArrayBindingPattern)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -16031,7 +16415,7 @@ namespace ts { // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. - return (functionFlags & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async + return (functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async ? createPromiseReturnType(func, widenedType) // Async function : widenedType; // Generator function, AsyncGenerator function, or normal function } @@ -16247,7 +16631,7 @@ namespace ts { const functionFlags = getFunctionFlags(node); const returnOrPromisedType = node.type && - ((functionFlags & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async ? + ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async ? checkAsyncFunctionReturnType(node) : // Async function getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function @@ -16277,7 +16661,7 @@ namespace ts { // its return type annotation. const exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async) { // Async function + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async) { // Async function const awaitedType = checkAwaitedType(exprType, node.body, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } @@ -16403,7 +16787,7 @@ namespace ts { return silentNeverType; } if (node.operator === SyntaxKind.MinusToken && node.operand.kind === SyntaxKind.NumericLiteral) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(TypeFlags.NumberLiteral, "" + -(node.operand).text)); + return getFreshTypeOfLiteralType(getLiteralType(-(node.operand).text)); } switch (node.operator) { case SyntaxKind.PlusToken: @@ -16911,7 +17295,7 @@ namespace ts { return checkInExpression(left, right, leftType, rightType); case SyntaxKind.AmpersandAmpersandToken: return getTypeFacts(leftType) & TypeFacts.Truthy ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case SyntaxKind.BarBarToken: return getTypeFacts(leftType) & TypeFacts.Falsy ? @@ -16962,7 +17346,7 @@ namespace ts { } function checkAssignmentOperator(valueType: Type): void { - if (produceDiagnostics && operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment) { + if (produceDiagnostics && isAssignmentOperator(operator)) { // TypeScript 1.0 spec (April 2014): 4.17 // An assignment of the form // VarExpr = ValueExpr @@ -17017,12 +17401,16 @@ namespace ts { // we are in a yield context. const functionFlags = func && getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & FunctionFlags.Async) { - if (languageVersion < ScriptTarget.ES2017) { - checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncDelegator); - } + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.AsyncGenerator && + languageVersion < ScriptTarget.ESNext) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncDelegatorIncludes); } - else if (languageVersion < ScriptTarget.ES2015 && compilerOptions.downlevelIteration) { + + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Generator && + languageVersion < ScriptTarget.ES2015 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, ExternalEmitHelpers.Values); } } @@ -17079,9 +17467,9 @@ namespace ts { } switch (node.kind) { case SyntaxKind.StringLiteral: - return getFreshTypeOfLiteralType(getLiteralTypeForText(TypeFlags.StringLiteral, (node).text)); + return getFreshTypeOfLiteralType(getLiteralType((node).text)); case SyntaxKind.NumericLiteral: - return getFreshTypeOfLiteralType(getLiteralTypeForText(TypeFlags.NumberLiteral, (node).text)); + return getFreshTypeOfLiteralType(getLiteralType(+(node).text)); case SyntaxKind.TrueKeyword: return trueType; case SyntaxKind.FalseKeyword: @@ -17545,18 +17933,20 @@ namespace ts { } const functionFlags = getFunctionFlags(node); - if ((functionFlags & FunctionFlags.InvalidAsyncOrAsyncGenerator) === FunctionFlags.Async && languageVersion < ScriptTarget.ES2017) { - checkExternalEmitHelpers(node, ExternalEmitHelpers.Awaiter); - if (languageVersion < ScriptTarget.ES2015) { - checkExternalEmitHelpers(node, ExternalEmitHelpers.Generator); + if (!(functionFlags & FunctionFlags.Invalid)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.AsyncGenerator && languageVersion < ScriptTarget.ESNext) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncGeneratorIncludes); } - } - if ((functionFlags & FunctionFlags.InvalidGenerator) === FunctionFlags.Generator) { - if (functionFlags & FunctionFlags.Async && languageVersion < ScriptTarget.ES2017) { - checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncGenerator); + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async && languageVersion < ScriptTarget.ES2017) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.Awaiter); } - else if (languageVersion < ScriptTarget.ES2015) { + + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & FunctionFlags.AsyncGenerator) !== FunctionFlags.Normal && languageVersion < ScriptTarget.ES2015) { checkExternalEmitHelpers(node, ExternalEmitHelpers.Generator); } } @@ -17584,7 +17974,7 @@ namespace ts { if (node.type) { const functionFlags = getFunctionFlags(node); - if ((functionFlags & FunctionFlags.InvalidGenerator) === FunctionFlags.Generator) { + if ((functionFlags & (FunctionFlags.Invalid | FunctionFlags.Generator)) === FunctionFlags.Generator) { const returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -17604,7 +17994,7 @@ namespace ts { checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } - else if ((functionFlags & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async) { + else if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async) { checkAsyncFunctionReturnType(node); } } @@ -17728,7 +18118,7 @@ namespace ts { } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, Diagnostics.Duplicate_identifier_0, memberName); + error(getNameOfDeclaration(member.symbol.valueDeclaration), Diagnostics.Duplicate_identifier_0, memberName); error(member.name, Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -17829,7 +18219,8 @@ namespace ts { } function containsSuperCallAsComputedPropertyName(n: Declaration): boolean { - return n.name && containsSuperCall(n.name); + const name = getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n: Node): boolean { @@ -17932,7 +18323,7 @@ namespace ts { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. const otherKind = node.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; - const otherAccessor = getDeclarationOfKind(node.symbol, otherKind); + const otherAccessor = getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { if ((getModifierFlags(node) & ModifierFlags.AccessibilityModifier) !== (getModifierFlags(otherAccessor) & ModifierFlags.AccessibilityModifier)) { error(node.name, Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); @@ -18004,7 +18395,7 @@ namespace ts { checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & TypeFlags.Enum && !(type).memberTypes && getNodeLinks(node).resolvedSymbol.flags & SymbolFlags.EnumMember) { + if (type.flags & TypeFlags.Enum && getNodeLinks(node).resolvedSymbol.flags & SymbolFlags.EnumMember) { error(node, Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -18124,16 +18515,16 @@ namespace ts { forEach(overloads, o => { const deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; if (deviation & ModifierFlags.Export) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & ModifierFlags.Ambient) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (ModifierFlags.Private | ModifierFlags.Protected)) { - error(o.name || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(getNameOfDeclaration(o) || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & ModifierFlags.Abstract) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -18145,7 +18536,7 @@ namespace ts { forEach(overloads, o => { const deviation = hasQuestionToken(o) !== canonicalHasQuestionToken; if (deviation) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -18281,7 +18672,7 @@ namespace ts { if (duplicateFunctionDeclaration) { forEach(declarations, declaration => { - error(declaration.name, Diagnostics.Duplicate_function_implementation); + error(getNameOfDeclaration(declaration), Diagnostics.Duplicate_function_implementation); }); } @@ -18363,12 +18754,13 @@ namespace ts { for (const d of symbol.declarations) { const declarationSpaces = getDeclarationSpaces(d); + const name = getNameOfDeclaration(d); // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(d.name)); + error(name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(d.name)); + error(name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(name)); } } } @@ -18734,7 +19126,10 @@ namespace ts { * marked as referenced to prevent import elision. */ function markTypeNodeAsReferenced(node: TypeNode) { - const typeName = node && getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && getEntityNameFromTypeNode(node)); + } + + function markEntityNameOrEntityExpressionAsReference(typeName: EntityNameOrEntityNameExpression) { const rootName = typeName && getFirstIdentifier(typeName); const rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === SyntaxKind.Identifier ? SymbolFlags.Type : SymbolFlags.Namespace) | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (rootSymbol @@ -18745,6 +19140,61 @@ namespace ts { } } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ + function markDecoratorMedataDataTypeNodeAsReferenced(node: TypeNode): void { + const entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + + function getEntityNameForDecoratorMetadata(node: TypeNode): EntityName { + if (node) { + switch (node.kind) { + case SyntaxKind.IntersectionType: + case SyntaxKind.UnionType: + let commonEntityName: EntityName; + for (const typeNode of (node).types) { + const individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!isIdentifier(commonEntityName) || + !isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + + case SyntaxKind.ParenthesizedType: + return getEntityNameForDecoratorMetadata((node).type); + + case SyntaxKind.TypeReference: + return (node).typeName; + } + } + } + function getParameterTypeNodeForDecoratorCheck(node: ParameterDeclaration): TypeNode { return node.dotDotDotToken ? getRestParameterElementType(node.type) : node.type; } @@ -18780,7 +19230,7 @@ namespace ts { const constructor = getFirstConstructorWithBody(node); if (constructor) { for (const parameter of constructor.parameters) { - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -18789,17 +19239,17 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: for (const parameter of (node).parameters) { - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced((node).type); + markDecoratorMedataDataTypeNodeAsReferenced((node).type); break; case SyntaxKind.PropertyDeclaration: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case SyntaxKind.Parameter: - markTypeNodeAsReferenced((node).type); + markDecoratorMedataDataTypeNodeAsReferenced((node).type); break; } } @@ -18949,15 +19399,16 @@ namespace ts { if (!local.isReferenced) { if (local.valueDeclaration && getRootDeclaration(local.valueDeclaration).kind === SyntaxKind.Parameter) { const parameter = getRootDeclaration(local.valueDeclaration); + const name = getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !isParameterPropertyDeclaration(parameter) && !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - forEach(local.declarations, d => errorUnusedLocal(d.name || d, local.name)); + forEach(local.declarations, d => errorUnusedLocal(getNameOfDeclaration(d) || d, local.name)); } } }); @@ -19041,7 +19492,7 @@ namespace ts { if (!local.isReferenced && !local.exportSymbol) { for (const declaration of local.declarations) { if (!isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(getNameOfDeclaration(declaration), local.name); } } } @@ -19120,7 +19571,7 @@ namespace ts { if (getNodeCheckFlags(current) & NodeCheckFlags.CaptureThis) { const isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { - error((node).name, Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -19135,7 +19586,7 @@ namespace ts { if (getNodeCheckFlags(current) & NodeCheckFlags.CaptureNewTarget) { const isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { - error((node).name, Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -19434,7 +19885,7 @@ namespace ts { checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); + error(getNameOfDeclaration(symbol.valueDeclaration), Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); } } @@ -19571,11 +20022,14 @@ namespace ts { if (node.kind === SyntaxKind.ForOfStatement) { if ((node).awaitModifier) { - if (languageVersion < ScriptTarget.ES2017) { + const functionFlags = getFunctionFlags(getContainingFunction(node)); + if ((functionFlags & (FunctionFlags.Invalid | FunctionFlags.Async)) === FunctionFlags.Async && languageVersion < ScriptTarget.ESNext) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper checkExternalEmitHelpers(node, ExternalEmitHelpers.ForAwaitOfIncludes); } } - else if (languageVersion < ScriptTarget.ES2015 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < ScriptTarget.ES2015) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled checkExternalEmitHelpers(node, ExternalEmitHelpers.ForOfIncludes); } } @@ -20001,11 +20455,11 @@ namespace ts { } function isGetAccessorWithAnnotatedSetAccessor(node: FunctionLikeDeclaration) { - return !!(node.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(node.symbol, SyntaxKind.SetAccessor))); + return !!(node.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(node.symbol, SyntaxKind.SetAccessor))); } function isUnwrappedReturnTypeVoidOrAny(func: FunctionLikeDeclaration, returnType: Type): boolean { - const unwrappedReturnType = (getFunctionFlags(func) & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async + const unwrappedReturnType = (getFunctionFlags(func) & FunctionFlags.AsyncGenerator) === FunctionFlags.Async ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, TypeFlags.Void | TypeFlags.Any); @@ -20262,14 +20716,17 @@ namespace ts { const propDeclaration = prop.valueDeclaration; // index is numeric and property name is not valid numeric literal - if (indexKind === IndexKind.Number && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === IndexKind.Number && !(propDeclaration ? isNumericName(getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } // perform property check if property or indexer is declared in 'type' - // this allows to rule out cases when both property and indexer are inherited from the base class + // this allows us to rule out cases when both property and indexer are inherited from the base class let errorNode: Node; - if (propDeclaration && (propDeclaration.name.kind === SyntaxKind.ComputedPropertyName || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === SyntaxKind.BinaryExpression || + getNameOfDeclaration(propDeclaration).kind === SyntaxKind.ComputedPropertyName || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -20606,11 +21063,6 @@ namespace ts { continue; } - if ((baseDeclarationFlags & ModifierFlags.Static) !== (derivedDeclarationFlags & ModifierFlags.Static)) { - // value of 'static' is not the same for properties - not override, skip it - continue; - } - if (isMethodLike(base) && isMethodLike(derived) || base.flags & SymbolFlags.PropertyOrAccessor && derived.flags & SymbolFlags.PropertyOrAccessor) { // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; @@ -20632,7 +21084,7 @@ namespace ts { errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -20691,7 +21143,7 @@ namespace ts { checkTypeParameterListsIdentical(symbol); // Only check this symbol once - const firstInterfaceDecl = getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); + const firstInterfaceDecl = getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); if (node === firstInterfaceDecl) { const type = getDeclaredTypeOfSymbol(symbol); const typeWithThis = getTypeWithThisArgument(type); @@ -20731,107 +21183,91 @@ namespace ts { function computeEnumMemberValues(node: EnumDeclaration) { const nodeLinks = getNodeLinks(node); - if (!(nodeLinks.flags & NodeCheckFlags.EnumValuesComputed)) { - const enumSymbol = getSymbolOfNode(node); - const enumType = getDeclaredTypeOfSymbol(enumSymbol); - let autoValue = 0; // set to undefined when enum member is non-constant - const ambient = isInAmbientContext(node); - const enumIsConst = isConst(node); - - for (const member of node.members) { - if (isComputedNonLiteralName(member.name)) { - error(member.name, Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - const text = getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - - const previousEnumMemberIsNonConstant = autoValue === undefined; - - const initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - // In ambient enum declarations that specify no const modifier, enum member declarations - // that omit a value are considered computed members (as opposed to having auto-incremented values assigned). - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - // If the member declaration specifies no value, the member is considered a constant enum member. - // If the member is the first member in the enum declaration, it is assigned the value zero. - // Otherwise, it is assigned the value of the immediately preceding member plus one, - // and an error occurs if the immediately preceding member is not a constant enum member - error(member.name, Diagnostics.Enum_member_must_have_initializer); - } - - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } - } - nodeLinks.flags |= NodeCheckFlags.EnumValuesComputed; - } - - function computeConstantValueForEnumMemberInitializer(initializer: Expression, enumType: Type, enumIsConst: boolean, ambient: boolean): number { - // Controls if error should be reported after evaluation of constant value is completed - // Can be false if another more precise error was already reported during evaluation. - let reportError = true; - const value = evalConstant(initializer); - - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + let autoValue = 0; + for (const member of node.members) { + const value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } + } + } - return value; + function computeMemberValue(member: EnumMember, autoValue: number) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + const text = getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } + } + if (member.initializer) { + return computeConstantValue(member); + } + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (isInAmbientContext(member.parent) && !isConst(member.parent)) { + return undefined; + } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, Diagnostics.Enum_member_must_have_initializer); + return undefined; + } - function evalConstant(e: Node): number { - switch (e.kind) { - case SyntaxKind.PrefixUnaryExpression: - const value = evalConstant((e).operand); - if (value === undefined) { - return undefined; - } - switch ((e).operator) { + function computeConstantValue(member: EnumMember): string | number { + const enumKind = getEnumKind(getSymbolOfNode(member.parent)); + const isConstEnum = isConst(member.parent); + const initializer = member.initializer; + const value = enumKind === EnumKind.Literal && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === EnumKind.Literal) { + error(initializer, Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (isInAmbientContext(member.parent)) { + error(initializer, Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + // Only here do we need to check that the initializer is assignable to the enum type. + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } + return value; + + function evaluate(expr: Expression): string | number { + switch (expr.kind) { + case SyntaxKind.PrefixUnaryExpression: + const value = evaluate((expr).operand); + if (typeof value === "number") { + switch ((expr).operator) { case SyntaxKind.PlusToken: return value; case SyntaxKind.MinusToken: return -value; case SyntaxKind.TildeToken: return ~value; } - return undefined; - case SyntaxKind.BinaryExpression: - const left = evalConstant((e).left); - if (left === undefined) { - return undefined; - } - const right = evalConstant((e).right); - if (right === undefined) { - return undefined; - } - switch ((e).operatorToken.kind) { + } + break; + case SyntaxKind.BinaryExpression: + const left = evaluate((expr).left); + const right = evaluate((expr).right); + if (typeof left === "number" && typeof right === "number") { + switch ((expr).operatorToken.kind) { case SyntaxKind.BarToken: return left | right; case SyntaxKind.AmpersandToken: return left & right; case SyntaxKind.GreaterThanGreaterThanToken: return left >> right; @@ -20844,90 +21280,56 @@ namespace ts { case SyntaxKind.MinusToken: return left - right; case SyntaxKind.PercentToken: return left % right; } - return undefined; - case SyntaxKind.NumericLiteral: - checkGrammarNumericLiteral(e); - return +(e).text; - case SyntaxKind.ParenthesizedExpression: - return evalConstant((e).expression); - case SyntaxKind.Identifier: - case SyntaxKind.ElementAccessExpression: - case SyntaxKind.PropertyAccessExpression: - const member = initializer.parent; - const currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - let enumType: Type; - let propertyName: string; - - if (e.kind === SyntaxKind.Identifier) { - // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. - // instead pick current enum type and later try to fetch member from the type - enumType = currentType; - propertyName = (e).text; + } + break; + case SyntaxKind.StringLiteral: + return (expr).text; + case SyntaxKind.NumericLiteral: + checkGrammarNumericLiteral(expr); + return +(expr).text; + case SyntaxKind.ParenthesizedExpression: + return evaluate((expr).expression); + case SyntaxKind.Identifier: + return nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), (expr).text); + case SyntaxKind.ElementAccessExpression: + case SyntaxKind.PropertyAccessExpression: + if (isConstantMemberAccess(expr)) { + const type = getTypeOfExpression((expr).expression); + if (type.symbol && type.symbol.flags & SymbolFlags.Enum) { + const name = expr.kind === SyntaxKind.PropertyAccessExpression ? + (expr).name.text : + ((expr).argumentExpression).text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - let expression: Expression; - if (e.kind === SyntaxKind.ElementAccessExpression) { - if ((e).argumentExpression === undefined || - (e).argumentExpression.kind !== SyntaxKind.StringLiteral) { - return undefined; - } - expression = (e).expression; - propertyName = ((e).argumentExpression).text; - } - else { - expression = (e).expression; - propertyName = (e).name.text; - } + } + break; + } + return undefined; + } - // expression part in ElementAccess\PropertyAccess should be either identifier or dottedName - let current = expression; - while (current) { - if (current.kind === SyntaxKind.Identifier) { - break; - } - else if (current.kind === SyntaxKind.PropertyAccessExpression) { - current = (current).expression; - } - else { - return undefined; - } - } - - enumType = getTypeOfExpression(expression); - // allow references to constant members of other enums - if (!(enumType.symbol && (enumType.symbol.flags & SymbolFlags.Enum))) { - return undefined; - } - } - - if (propertyName === undefined) { - return undefined; - } - - const property = getPropertyOfObjectType(enumType, propertyName); - if (!property || !(property.flags & SymbolFlags.EnumMember)) { - return undefined; - } - - const propertyDecl = property.valueDeclaration; - // self references are illegal - if (member === propertyDecl) { - return undefined; - } - - // illegal case: forward reference - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - - return getNodeLinks(propertyDecl).enumMemberValue; + function evaluateEnumMember(expr: Expression, enumSymbol: Symbol, name: string) { + const memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + const declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + error(expr, Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return 0; } } + return undefined; } } + function isConstantMemberAccess(node: Expression): boolean { + return node.kind === SyntaxKind.Identifier || + node.kind === SyntaxKind.PropertyAccessExpression && isConstantMemberAccess((node).expression) || + node.kind === SyntaxKind.ElementAccessExpression && isConstantMemberAccess((node).expression) && + (node).argumentExpression.kind === SyntaxKind.StringLiteral; + } + function checkEnumDeclaration(node: EnumDeclaration) { if (!produceDiagnostics) { return; @@ -20963,7 +21365,7 @@ namespace ts { // check that const is placed\omitted on all enum declarations forEach(enumSymbol.declarations, decl => { if (isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(getNameOfDeclaration(decl), Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -21237,6 +21639,11 @@ namespace ts { Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + + // Don't allow to re-export something with no value side when `--isolatedModules` is set. + if (node.kind === SyntaxKind.ExportSpecifier && compilerOptions.isolatedModules && !(target.flags & SymbolFlags.Value)) { + error(node, Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } @@ -21856,7 +22263,7 @@ namespace ts { function isTypeDeclarationName(name: Node): boolean { return name.kind === SyntaxKind.Identifier && isTypeDeclaration(name.parent) && - (name.parent).name === name; + (name.parent).name === name; } function isTypeDeclaration(node: Node): boolean { @@ -21991,6 +22398,11 @@ namespace ts { } } + if (entityName.parent!.kind === SyntaxKind.JSDocParameterTag) { + const parameter = ts.getParameterFromJSDoc(entityName.parent as JSDocParameterTag); + return parameter && parameter.symbol; + } + if (isPartOfExpression(entityName)) { if (nodeIsMissing(entityName)) { // Missing entity name. @@ -22045,7 +22457,7 @@ namespace ts { return undefined; } - if (isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode return getSymbolOfNode(node.parent); } @@ -22192,7 +22604,7 @@ namespace ts { return getTypeOfSymbol(symbol); } - if (isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { const symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -22402,7 +22814,7 @@ namespace ts { const symbolIsUmdExport = symbolFile !== referenceFile; return symbolIsUmdExport ? undefined : symbolFile; } - return findAncestor(node.parent, n => isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol) as ModuleDeclaration | EnumDeclaration; + return findAncestor(node.parent, (n): n is ModuleDeclaration | EnumDeclaration => isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol); } } } @@ -22588,7 +23000,7 @@ namespace ts { return getNodeLinks(node).flags; } - function getEnumMemberValue(node: EnumMember): number { + function getEnumMemberValue(node: EnumMember): string | number { computeEnumMemberValues(node.parent); return getNodeLinks(node).enumMemberValue; } @@ -22603,7 +23015,7 @@ namespace ts { return false; } - function getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number { + function getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number { if (node.kind === SyntaxKind.EnumMember) { return getEnumMemberValue(node); } @@ -22688,7 +23100,7 @@ namespace ts { ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & TypeFormatFlags.AddUndefined) { - type = includeFalsyTypes(type, TypeFlags.Undefined); + type = getNullableType(type, TypeFlags.Undefined); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -22703,16 +23115,6 @@ namespace ts { getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { - const classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - const baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } - function hasGlobalName(name: string): boolean { return globals.has(name); } @@ -22806,7 +23208,6 @@ namespace ts { writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression, - writeBaseConstructorTypeOfClass, isSymbolAccessible, isEntityNameVisible, getConstantValue: node => { @@ -23012,6 +23413,7 @@ namespace ts { case ExternalEmitHelpers.Values: return "__values"; case ExternalEmitHelpers.Read: return "__read"; case ExternalEmitHelpers.Spread: return "__spread"; + case ExternalEmitHelpers.Await: return "__await"; case ExternalEmitHelpers.AsyncGenerator: return "__asyncGenerator"; case ExternalEmitHelpers.AsyncDelegator: return "__asyncDelegator"; case ExternalEmitHelpers.AsyncValues: return "__asyncValues"; @@ -24252,4 +24654,19 @@ namespace ts { } } } -} \ No newline at end of file + + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ + function isDeclarationNameOrImportPropertyName(name: Node): boolean { + switch (name.parent.kind) { + case SyntaxKind.ImportSpecifier: + case SyntaxKind.ExportSpecifier: + if ((name.parent as ImportOrExportSpecifier).propertyName) { + return true; + } + // falls through + default: + return isDeclarationName(name); + + } + } +} diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 7abe311b79a..7fa42b94f2f 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -140,6 +140,7 @@ namespace ts { "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -1089,58 +1090,38 @@ namespace ts { * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ - export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: JsFileExtensionInfo[] = []): ParsedCommandLine { + export function parseJsonConfigFileContent( + json: any, + host: ParseConfigHost, + basePath: string, + existingOptions: CompilerOptions = {}, + configFileName?: string, + resolutionStack: Path[] = [], + extraFileExtensions: JsFileExtensionInfo[] = [], + ): ParsedCommandLine { const errors: Diagnostic[] = []; - basePath = normalizeSlashes(basePath); - const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))], - wildcardDirectories: {} - }; - } - let options: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); + let options = (() => { + const { include, exclude, files, options, compileOnSave } = parseConfig(json, host, basePath, configFileName, resolutionStack, errors); + if (include) { json.include = include; } + if (exclude) { json.exclude = exclude; } + if (files) { json.files = files; } + if (compileOnSave !== undefined) { json.compileOnSave = compileOnSave; } + return options; + })(); + + options = extend(existingOptions, options); + options.configFilePath = configFileName; + // typingOptions has been deprecated and is only supported for backward compatibility purposes. // It should be removed in future releases - use typeAcquisition instead. const jsonOptions = json["typeAcquisition"] || json["typingOptions"]; const typeAcquisition: TypeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - let baseCompileOnSave: boolean; - if (json["extends"]) { - let [include, exclude, files, baseOptions]: [string[], string[], string[], CompilerOptions] = [undefined, undefined, undefined, {}]; - if (typeof json["extends"] === "string") { - [include, exclude, files, baseCompileOnSave, baseOptions] = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]); - } - else { - errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); - } - if (include && !json["include"]) { - json["include"] = include; - } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; - } - if (files && !json["files"]) { - json["files"] = files; - } - options = assign({}, baseOptions, options); - } - - options = extend(existingOptions, options); - options.configFilePath = configFileName; - - const { fileNames, wildcardDirectories } = getFileNames(errors); - let compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } + const { fileNames, wildcardDirectories } = getFileNames(); + const compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options, @@ -1152,40 +1133,7 @@ namespace ts { compileOnSave }; - function tryExtendsName(extendedConfig: string): [string[], string[], string[], boolean, CompilerOptions] { - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(isRootedDiskPath(extendedConfig) || startsWith(normalizeSlashes(extendedConfig), "./") || startsWith(normalizeSlashes(extendedConfig), "../"))) { - errors.push(createCompilerDiagnostic(Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - let extendedConfigPath = toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = `${extendedConfigPath}.json` as Path; - if (!host.fileExists(extendedConfigPath)) { - errors.push(createCompilerDiagnostic(Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - const extendedResult = readConfigFile(extendedConfigPath, path => host.readFile(path)); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - const extendedDirname = getDirectoryPath(extendedConfigPath); - const relativeDifference = convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - const updatePath: (path: string) => string = path => isRootedDiskPath(path) ? path : combinePaths(relativeDifference, path); - // Merge configs (copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios) - const result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/ undefined, getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push(...result.errors); - const [include, exclude, files] = map(["include", "exclude", "files"], key => { - if (!json[key] && extendedResult.config[key]) { - return map(extendedResult.config[key], updatePath); - } - }); - return [include, exclude, files, result.compileOnSave, result.options]; - } - - function getFileNames(errors: Diagnostic[]): ExpandResult { + function getFileNames(): ExpandResult { let fileNames: string[]; if (hasProperty(json, "files")) { if (isArray(json["files"])) { @@ -1218,9 +1166,6 @@ namespace ts { errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (hasProperty(json, "excludes")) { - errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { // If no includes were specified, exclude common package folders and the outDir excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; @@ -1250,7 +1195,106 @@ namespace ts { } } - export function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined { + interface ParsedTsconfig { + include: string[] | undefined; + exclude: string[] | undefined; + files: string[] | undefined; + options: CompilerOptions; + compileOnSave: boolean | undefined; + } + + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig( + json: any, + host: ParseConfigHost, + basePath: string, + configFileName: string, + resolutionStack: Path[], + errors: Diagnostic[], + ): ParsedTsconfig { + + basePath = normalizeSlashes(basePath); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); + const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName); + + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + + if (hasProperty(json, "excludes")) { + errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + + let options: CompilerOptions = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + let include: string[] | undefined = json.include, exclude: string[] | undefined = json.exclude, files: string[] | undefined = json.files; + let compileOnSave: boolean | undefined = json.compileOnSave; + + if (json.extends) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + const base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = assign({}, base.options, options); + } + } + + return { include, exclude, files, options, compileOnSave }; + } + + function getExtendedConfig( + extended: any, // Usually a string. + host: ts.ParseConfigHost, + basePath: string, + getCanonicalFileName: (fileName: string) => string, + resolutionStack: Path[], + errors: Diagnostic[], + ): ParsedTsconfig | undefined { + if (typeof extended !== "string") { + errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + + extended = normalizeSlashes(extended); + + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) + if (!(isRootedDiskPath(extended) || startsWith(extended, "./") || startsWith(extended, "../"))) { + errors.push(createCompilerDiagnostic(Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + + let extendedConfigPath = toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json" as Path; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createCompilerDiagnostic(Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + + const extendedResult = readConfigFile(extendedConfigPath, path => host.readFile(path)); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + + const extendedDirname = getDirectoryPath(extendedConfigPath); + const relativeDifference = convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + const updatePath: (path: string) => string = path => isRootedDiskPath(path) ? path : combinePaths(relativeDifference, path); + const { include, exclude, files, options, compileOnSave } = parseConfig(extendedResult.config, host, extendedDirname, getBaseFileName(extendedConfigPath), resolutionStack, errors); + return { include: map(include, updatePath), exclude: map(exclude, updatePath), files: map(files, updatePath), compileOnSave, options }; + } + + export function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean { if (!hasProperty(jsonOption, compileOnSaveCommandLineOption.name)) { return false; } @@ -1662,4 +1706,4 @@ namespace ts { function caseInsensitiveKeyMapper(key: string) { return key.toLowerCase(); } -} \ No newline at end of file +} diff --git a/src/compiler/comments.ts b/src/compiler/comments.ts index c50cacc2ccb..06285309f64 100644 --- a/src/compiler/comments.ts +++ b/src/compiler/comments.ts @@ -58,8 +58,10 @@ namespace ts { } const isEmittedNode = node.kind !== SyntaxKind.NotEmittedStatement; - const skipLeadingComments = pos < 0 || (emitFlags & EmitFlags.NoLeadingComments) !== 0; - const skipTrailingComments = end < 0 || (emitFlags & EmitFlags.NoTrailingComments) !== 0; + // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. + // It is expensive to walk entire tree just to set one kind of node to have no comments. + const skipLeadingComments = pos < 0 || (emitFlags & EmitFlags.NoLeadingComments) !== 0 || node.kind === SyntaxKind.JsxText; + const skipTrailingComments = end < 0 || (emitFlags & EmitFlags.NoTrailingComments) !== 0 || node.kind === SyntaxKind.JsxText; // Emit leading comments if the position is not synthesized and the node // has not opted out from emitting leading comments. diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 321cc06f765..52a7b5f5a7a 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -230,6 +230,8 @@ namespace ts { * If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit" * At that point findAncestor returns undefined. */ + export function findAncestor(node: Node, callback: (element: Node) => element is T): T | undefined; + export function findAncestor(node: Node, callback: (element: Node) => boolean | "quit"): Node | undefined; export function findAncestor(node: Node, callback: (element: Node) => boolean | "quit"): Node { while (node) { const result = callback(node); @@ -490,6 +492,35 @@ namespace ts { return result; } + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * Avoids allocation if all elements map to themselves. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + export function sameFlatMap(array: T[], mapfn: (x: T, i: number) => T | T[]): T[] { + let result: T[]; + if (array) { + for (let i = 0; i < array.length; i++) { + const item = array[i]; + const mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -1733,6 +1764,11 @@ namespace ts { return str.lastIndexOf(prefix, 0) === 0; } + /* @internal */ + export function removePrefix(str: string, prefix: string): string { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + /* @internal */ export function endsWith(str: string, suffix: string): boolean { const expectedPos = str.length - suffix.length; @@ -1747,7 +1783,8 @@ namespace ts { return path.length > extension.length && endsWith(path, extension); } - export function fileExtensionIsAny(path: string, extensions: string[]): boolean { + /* @internal */ + export function fileExtensionIsOneOf(path: string, extensions: string[]): boolean { for (const extension of extensions) { if (fileExtensionIs(path, extension)) { return true; @@ -1947,7 +1984,7 @@ namespace ts { for (const current of files) { const name = combinePaths(path, current); const absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsAny(name, extensions)) continue; + if (extensions && !fileExtensionIsOneOf(name, extensions)) continue; if (excludeRegex && excludeRegex.test(absoluteName)) continue; if (!includeFileRegexes) { results[0].push(name); diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 2bd8d5971fb..987157843b6 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -67,7 +67,7 @@ namespace ts { let errorNameNode: DeclarationName; const emitJsDocComments = compilerOptions.removeComments ? noop : writeJsDocComments; const emit = compilerOptions.stripInternal ? stripInternal : emitNode; - let noDeclare: boolean; + let needsDeclare = true; let moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = []; let asynchronousSubModuleDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[]; @@ -110,11 +110,11 @@ namespace ts { resultHasExternalModuleIndicator = false; if (!isBundledEmit || !isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write(`declare module "${getResolvedExternalModuleName(host, sourceFile)}" {`); writeLine(); increaseIndent(); @@ -190,7 +190,7 @@ namespace ts { const writer = createTextWriter(newLine); writer.trackSymbol = trackSymbol; writer.reportInaccessibleThisError = reportInaccessibleThisError; - writer.reportIllegalExtends = reportIllegalExtends; + writer.reportPrivateInBaseOfClassExpression = reportPrivateInBaseOfClassExpression; writer.writeKeyword = writer.write; writer.writeOperator = writer.write; writer.writePunctuation = writer.write; @@ -314,11 +314,11 @@ namespace ts { recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } - function reportIllegalExtends() { + function reportPrivateInBaseOfClassExpression(propertyName: string) { if (errorNameNode) { reportedDeclarationError = true; - emitterDiagnostics.add(createDiagnosticForNode(errorNameNode, Diagnostics.extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced, - declarationNameToString(errorNameNode))); + emitterDiagnostics.add( + createDiagnosticForNode(errorNameNode, Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } @@ -344,7 +344,9 @@ namespace ts { } else { errorNameNode = declaration.name; - const format = TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue | + const format = TypeFormatFlags.UseTypeOfFunction | + TypeFormatFlags.WriteClassExpressionAsTypeLiteral | + TypeFormatFlags.UseTypeAliasValue | (shouldUseResolverType ? TypeFormatFlags.AddUndefined : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; @@ -360,7 +362,11 @@ namespace ts { } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer); + resolver.writeReturnTypeOfSignatureDeclaration( + signature, + enclosingDeclaration, + TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue | TypeFormatFlags.WriteClassExpressionAsTypeLiteral, + writer); errorNameNode = undefined; } } @@ -594,12 +600,11 @@ namespace ts { emitLines(node.statements); } - // Return a temp variable name to be used in `export default` statements. + // Return a temp variable name to be used in `export default`/`export class ... extends` statements. // The temp name will be of the form _default_counter. // Note that export default is only allowed at most once in a module, so we // do not need to keep track of created temp names. - function getExportDefaultTempVariableName(): string { - const baseName = "_default"; + function getExportTempVariableName(baseName: string): string { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -613,24 +618,35 @@ namespace ts { } } + function emitTempVariableDeclaration(expr: Expression, baseName: string, diagnostic: SymbolAccessibilityDiagnostic, needsDeclare: boolean): string { + const tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = () => diagnostic; + resolver.writeTypeOfExpression( + expr, + enclosingDeclaration, + TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue | TypeFormatFlags.WriteClassExpressionAsTypeLiteral, + writer); + write(";"); + writeLine(); + return tempVarName; + } + function emitExportAssignment(node: ExportAssignment) { if (node.expression.kind === SyntaxKind.Identifier) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - // Expression - const tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer); - write(";"); - writeLine(); + const tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -644,13 +660,6 @@ namespace ts { // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } - - function getDefaultExportAccessibilityDiagnostic(): SymbolAccessibilityDiagnostic { - return { - diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node: Declaration) { @@ -729,7 +738,7 @@ namespace ts { if (modifiers & ModifierFlags.Default) { write("default "); } - else if (node.kind !== SyntaxKind.InterfaceDeclaration && !noDeclare) { + else if (node.kind !== SyntaxKind.InterfaceDeclaration && needsDeclare) { write("declare "); } } @@ -985,7 +994,7 @@ namespace ts { const enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -1097,7 +1106,7 @@ namespace ts { } } - function emitHeritageClause(className: Identifier, typeReferences: ExpressionWithTypeArguments[], isImplementsList: boolean) { + function emitHeritageClause(typeReferences: ExpressionWithTypeArguments[], isImplementsList: boolean) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -1110,12 +1119,6 @@ namespace ts { else if (!isImplementsList && node.expression.kind === SyntaxKind.NullKeyword) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError(): SymbolAccessibilityDiagnostic { let diagnosticMessage: DiagnosticMessage; @@ -1134,7 +1137,7 @@ namespace ts { return { diagnosticMessage, errorNode: node, - typeName: (node.parent.parent).name + typeName: getNameOfDeclaration(node.parent.parent) }; } } @@ -1151,23 +1154,43 @@ namespace ts { } } + const prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + const baseTypeNode = getClassExtendsHeritageClauseElement(node); + let tempVarName: string; + if (baseTypeNode && !isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === SyntaxKind.NullKeyword ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, `${node.name.text}_base`, { + diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !findAncestor(node, n => n.kind === SyntaxKind.ModuleDeclaration)); + } + emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (hasModifier(node, ModifierFlags.Abstract)) { write("abstract "); } - write("class "); writeTextOfNode(currentText, node.name); - const prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - const baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false); + if (!isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); + } } - emitHeritageClause(node.name, getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); + emitHeritageClause(getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); write(" {"); writeLine(); increaseIndent(); @@ -1189,7 +1212,7 @@ namespace ts { emitTypeParameters(node.typeParameters); const interfaceExtendsTypes = filter(getInterfaceBaseTypeNodes(node), base => isEntityNameExpression(base.expression)); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, /*isImplementsList*/ false); + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); } write(" {"); writeLine(); @@ -1253,7 +1276,9 @@ namespace ts { Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit - else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) { + // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. + else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || + (node.kind === SyntaxKind.Parameter && hasModifier(node.parent, ModifierFlags.Private))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (hasModifier(node, ModifierFlags.Static)) { return symbolAccessibilityResult.errorModuleName ? @@ -1262,7 +1287,7 @@ namespace ts { Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === SyntaxKind.ClassDeclaration) { + else if (node.parent.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.Parameter) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -1488,6 +1513,11 @@ namespace ts { write("["); } else { + if (node.kind === SyntaxKind.Constructor && hasModifier(node, ModifierFlags.Private)) { + write("();"); + writeLine(); + return; + } // Construct signature or constructor type write new Signature if (node.kind === SyntaxKind.ConstructSignature || node.kind === SyntaxKind.ConstructorType) { write("new "); @@ -1820,7 +1850,7 @@ namespace ts { function writeReferencePath(referencedFile: SourceFile, addBundledFileReference: boolean, emitOnlyDtsFiles: boolean): boolean { let declFileName: string; let addedBundledEmitReference = false; - if (isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { // Declaration file, use declaration file name declFileName = referencedFile.fileName; } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 29f00e85f89..70a3465a6ee 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -635,6 +635,10 @@ "category": "Error", "code": 1203 }, + "Cannot re-export a type when the '--isolatedModules' flag is provided.": { + "category": "Error", + "code": 1205 + }, "Decorators are not valid here.": { "category": "Error", "code": 1206 @@ -1080,7 +1084,7 @@ "category": "Error", "code": 2345 }, - "Supplied parameters do not match any signature of call target.": { + "Call target does not contain any signatures.": { "category": "Error", "code": 2346 }, @@ -1860,6 +1864,38 @@ "category": "Error", "code": 2550 }, + "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?": { + "category": "Error", + "code": 2551 + }, + "Cannot find name '{0}'. Did you mean '{1}'?": { + "category": "Error", + "code": 2552 + }, + "Computed values are not permitted in an enum with string valued members.": { + "category": "Error", + "code": 2553 + }, + "Expected {0} arguments, but got {1}.": { + "category": "Error", + "code": 2554 + }, + "Expected at least {0} arguments, but got {1}.": { + "category": "Error", + "code": 2555 + }, + "Expected {0} arguments, but got a minimum of {1}.": { + "category": "Error", + "code": 2556 + }, + "Expected at least {0} arguments, but got a minimum of {1}.": { + "category": "Error", + "code": 2557 + }, + "Expected {0} type arguments, but got {1}.": { + "category": "Error", + "code": 2558 + }, "JSX element attributes type '{0}' may not be a union type.": { "category": "Error", "code": 2600 @@ -2441,9 +2477,9 @@ "category": "Error", "code": 4092 }, - "'extends' clause of exported class '{0}' refers to a type whose name cannot be referenced.": { + "Property '{0}' of exported class expression may not be private or protected.": { "category": "Error", - "code": 4093 + "code": 4094 }, "The current host does not support the '{0}' option.": { @@ -3046,6 +3082,10 @@ "category": "Message", "code": 6136 }, + "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'.": { + "category": "Error", + "code": 6137 + }, "Property '{0}' is declared but never used.": { "category": "Error", "code": 6138 @@ -3565,7 +3605,19 @@ "category": "Message", "code": 90021 }, + "Change spelling to '{0}'.": { + "category": "Message", + "code": 90022 + }, + "Convert function to an ES2015 class": { + "category": "Message", + "code": 95001 + }, + "Convert function '{0}' to class": { + "category": "Message", + "code": 95002 + }, "Octal literal types must use ES2015 syntax. Use the syntax '{0}'.": { "category": "Error", diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index d7a5c6f1612..01fcba2b896 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -153,7 +153,7 @@ namespace ts { for (let i = 0; i < numNodes; i++) { const currentNode = bundle ? bundle.sourceFiles[i] : node; const sourceFile = isSourceFile(currentNode) ? currentNode : currentSourceFile; - const shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && getExternalHelpersModuleName(sourceFile) !== undefined); + const shouldSkip = compilerOptions.noEmitHelpers || getExternalHelpersModuleName(sourceFile) !== undefined; const shouldBundle = isSourceFile(currentNode) && !isOwnFileEmit; const helpers = getEmitHelpers(currentNode); if (helpers) { @@ -200,7 +200,9 @@ namespace ts { onSetSourceFile, substituteNode, onBeforeEmitNodeArray, - onAfterEmitNodeArray + onAfterEmitNodeArray, + onBeforeEmitToken, + onAfterEmitToken } = handlers; const newLine = getNewLineCharacter(printerOptions); @@ -212,7 +214,7 @@ namespace ts { emitLeadingCommentsOfPosition, } = comments; - let currentSourceFile: SourceFile; + let currentSourceFile: SourceFile | undefined; let nodeIdToGeneratedName: string[]; // Map of generated names for specific nodes. let autoGeneratedIdToGeneratedName: string[]; // Map of generated names for temp and loop variables. let generatedNames: Map; // Set of names generated by the NameGenerator. @@ -264,7 +266,12 @@ namespace ts { return endPrint(); } - function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile, output: EmitTextWriter) { + /** + * If `sourceFile` is `undefined`, `node` must be a synthesized `TypeNode`. + */ + function writeNode(hint: EmitHint, node: TypeNode, sourceFile: undefined, output: EmitTextWriter): void; + function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile, output: EmitTextWriter): void; + function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, output: EmitTextWriter) { const previousWriter = writer; setWriter(output); print(hint, node, sourceFile); @@ -305,8 +312,10 @@ namespace ts { return text; } - function print(hint: EmitHint, node: Node, sourceFile: SourceFile) { - setSourceFile(sourceFile); + function print(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined) { + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } @@ -399,7 +408,7 @@ namespace ts { // Strict mode reserved words // Contextual keywords if (isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } @@ -562,6 +571,8 @@ namespace ts { return emitModuleBlock(node); case SyntaxKind.CaseBlock: return emitCaseBlock(node); + case SyntaxKind.NamespaceExportDeclaration: + return emitNamespaceExportDeclaration(node); case SyntaxKind.ImportEqualsDeclaration: return emitImportEqualsDeclaration(node); case SyntaxKind.ImportDeclaration: @@ -638,7 +649,7 @@ namespace ts { } if (isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -666,7 +677,7 @@ namespace ts { case SyntaxKind.TrueKeyword: case SyntaxKind.ThisKeyword: case SyntaxKind.ImportKeyword: - writeTokenText(kind); + writeTokenNode(node); return; // Expressions @@ -734,6 +745,9 @@ namespace ts { // Transformation nodes case SyntaxKind.PartiallyEmittedExpression: return emitPartiallyEmittedExpression(node); + + case SyntaxKind.CommaListExpression: + return emitCommaList(node); } } @@ -779,6 +793,7 @@ namespace ts { function emitIdentifier(node: Identifier) { write(getTextOfNode(node, /*includeTrivia*/ false)); + emitTypeArguments(node, node.typeArguments); } // @@ -813,6 +828,7 @@ namespace ts { function emitTypeParameter(node: TypeParameterDeclaration) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node: ParameterDeclaration) { @@ -847,6 +863,7 @@ namespace ts { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); write(";"); @@ -868,6 +885,7 @@ namespace ts { emitModifiers(node, node.modifiers); writeIfPresent(node.asteriskToken, "*"); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitSignatureAndBody(node, emitSignatureHead); } @@ -953,7 +971,10 @@ namespace ts { function emitTypeLiteral(node: TypeLiteralNode) { write("{"); - emitList(node, node.members, ListFormat.TypeLiteralMembers); + // If the literal is empty, do not add spaces between braces. + if (node.members.length > 0) { + emitList(node, node.members, getEmitFlags(node) & EmitFlags.SingleLine ? ListFormat.SingleLineTypeLiteralMembers : ListFormat.MultiLineTypeLiteralMembers); + } write("}"); } @@ -1000,9 +1021,15 @@ namespace ts { } function emitMappedType(node: MappedTypeNode) { + const emitFlags = getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & EmitFlags.SingleLine) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -1013,8 +1040,13 @@ namespace ts { write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & EmitFlags.SingleLine) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } @@ -1129,7 +1161,7 @@ namespace ts { // check if constant enum value is integer const constantValue = getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -1235,7 +1267,7 @@ namespace ts { const operand = node.operand; return operand.kind === SyntaxKind.PrefixUnaryExpression && ((node.operator === SyntaxKind.PlusToken && ((operand).operator === SyntaxKind.PlusToken || (operand).operator === SyntaxKind.PlusPlusToken)) - || (node.operator === SyntaxKind.MinusToken && ((operand).operator === SyntaxKind.MinusToken || (operand).operator === SyntaxKind.MinusMinusToken))); + || (node.operator === SyntaxKind.MinusToken && ((operand).operator === SyntaxKind.MinusToken || (operand).operator === SyntaxKind.MinusMinusToken))); } function emitPostfixUnaryExpression(node: PostfixUnaryExpression) { @@ -1250,7 +1282,7 @@ namespace ts { emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -1857,6 +1889,12 @@ namespace ts { write(";"); } + function emitNamespaceExportDeclaration(node: NamespaceExportDeclaration) { + write("export as namespace "); + emit(node.name); + write(";"); + } + function emitNamedExports(node: NamedExports) { emitNamedImportsOrExports(node); } @@ -1994,6 +2032,22 @@ namespace ts { rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile) ); + // e.g: + // case 0: // Zero + // case 1: // One + // case 2: // two + // return "hi"; + // If there is no statements, emitNodeWithComments of the parentNode which is caseClause will take care of trailing comment. + // So in example above, comment "// Zero" and "// One" will be emit in emitTrailingComments in emitNodeWithComments. + // However, for "case 2", because parentNode which is caseClause has an "end" property to be end of the statements (in this case return statement) + // comment "// two" will not be emitted in emitNodeWithComments. + // Therefore, we have to do the check here to emit such comment. + if (statements.length > 0) { + // We use emitTrailingCommentsOfPosition instead of emitLeadingCommentsOfPosition because leading comments is defined as comments before the node after newline character separating it from previous line + // Note: we can't use parentNode.end as such position includes statements. + emitTrailingCommentsOfPosition(statements.pos); + } + if (emitAsSingleStatement) { write(" "); emit(statements[0]); @@ -2102,6 +2156,10 @@ namespace ts { emitExpression(node.expression); } + function emitCommaList(node: CommaListExpression) { + emitExpressionList(node, node.elements, ListFormat.CommaListElements); + } + /** * Emits any prologue directives at the start of a Statement list, returning the * number of prologue directives written to the output. @@ -2426,6 +2484,16 @@ namespace ts { : writeTokenText(token, pos); } + function writeTokenNode(node: Node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } + function writeTokenText(token: SyntaxKind, pos?: number) { const tokenString = tokenToString(token); write(tokenString); @@ -2631,7 +2699,9 @@ namespace ts { if (node.kind === SyntaxKind.StringLiteral && (node).textSourceNode) { const textSourceNode = (node).textSourceNode; if (isIdentifier(textSourceNode)) { - return "\"" + escapeNonAsciiCharacters(escapeString(getTextOfNode(textSourceNode))) + "\""; + return getEmitFlags(node) & EmitFlags.NoAsciiEscaping ? + `"${escapeString(getTextOfNode(textSourceNode))}"` : + `"${escapeNonAsciiString(getTextOfNode(textSourceNode))}"`; } else { return getLiteralTextOfNode(textSourceNode); @@ -2897,9 +2967,9 @@ namespace ts { // Flags enum to track count of temp variables and a few dedicated names const enum TempFlags { - Auto = 0x00000000, // No preferred name + Auto = 0x00000000, // No preferred name CountMask = 0x0FFFFFFF, // Temp variable counter - _i = 0x10000000, // Use/preference flag for '_i' + _i = 0x10000000, // Use/preference flag for '_i' } const enum ListFormat { @@ -2944,7 +3014,9 @@ namespace ts { // Precomputed Formats Modifiers = SingleLine | SpaceBetweenSiblings, HeritageClauses = SingleLine | SpaceBetweenSiblings, - TypeLiteralMembers = MultiLine | Indented, + SingleLineTypeLiteralMembers = SingleLine | SpaceBetweenBraces | SpaceBetweenSiblings | Indented, + MultiLineTypeLiteralMembers = MultiLine | Indented, + TupleTypeElements = CommaDelimited | SpaceBetweenSiblings | SingleLine | Indented, UnionTypeConstituents = BarDelimited | SpaceBetweenSiblings | SingleLine, IntersectionTypeConstituents = AmpersandDelimited | SpaceBetweenSiblings | SingleLine, @@ -2952,6 +3024,7 @@ namespace ts { ArrayBindingPatternElements = SingleLine | AllowTrailingComma | CommaDelimited | SpaceBetweenSiblings, ObjectLiteralExpressionProperties = PreserveLines | CommaDelimited | SpaceBetweenSiblings | SpaceBetweenBraces | Indented | Braces, ArrayLiteralExpressionElements = PreserveLines | CommaDelimited | SpaceBetweenSiblings | AllowTrailingComma | Indented | SquareBrackets, + CommaListElements = CommaDelimited | SpaceBetweenSiblings | SingleLine, CallExpressionArguments = CommaDelimited | SpaceBetweenSiblings | SingleLine | Parenthesis, NewExpressionArguments = CommaDelimited | SpaceBetweenSiblings | SingleLine | Parenthesis | OptionalIfUndefined, TemplateExpressionSpans = SingleLine | NoInterveningComments, diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index cce95c23c22..2b41f13f8a4 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -107,15 +107,27 @@ namespace ts { // Identifiers - export function createIdentifier(text: string): Identifier { + export function createIdentifier(text: string): Identifier; + /* @internal */ + export function createIdentifier(text: string, typeArguments: TypeNode[]): Identifier; + export function createIdentifier(text: string, typeArguments?: TypeNode[]): Identifier { const node = createSynthesizedNode(SyntaxKind.Identifier); node.text = escapeIdentifier(text); node.originalKeywordKind = text ? stringToToken(text) : SyntaxKind.Unknown; node.autoGenerateKind = GeneratedIdentifierKind.None; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } + export function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + let nextAutoGenerateId = 0; /** Create a unique temporary variable. */ @@ -214,248 +226,14 @@ namespace ts { : node; } - // Type Elements - - export function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { - const signatureDeclaration = createSynthesizedNode(kind) as SignatureDeclaration; - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - - function updateSignatureDeclaration(node: SignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - - export function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { - return createSignatureDeclaration(SyntaxKind.FunctionType, typeParameters, parameters, type) as FunctionTypeNode; - } - - export function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - - export function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { - return createSignatureDeclaration(SyntaxKind.ConstructorType, typeParameters, parameters, type) as ConstructorTypeNode; - } - - export function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - - export function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { - return createSignatureDeclaration(SyntaxKind.CallSignature, typeParameters, parameters, type) as CallSignatureDeclaration; - } - - export function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - - export function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { - return createSignatureDeclaration(SyntaxKind.ConstructSignature, typeParameters, parameters, type) as ConstructSignatureDeclaration; - } - - export function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - - export function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined) { - const methodSignature = createSignatureDeclaration(SyntaxKind.MethodSignature, typeParameters, parameters, type) as MethodSignature; - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - - export function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - - // Types - - export function createKeywordTypeNode(kind: KeywordTypeNode["kind"]) { - return createSynthesizedNode(kind); - } - - export function createThisTypeNode() { - return createSynthesizedNode(SyntaxKind.ThisType); - } - - export function createLiteralTypeNode(literal: Expression) { - const literalTypeNode = createSynthesizedNode(SyntaxKind.LiteralType) as LiteralTypeNode; - literalTypeNode.literal = literal; - return literalTypeNode; - } - - export function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - - export function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined) { - const typeReference = createSynthesizedNode(SyntaxKind.TypeReference) as TypeReferenceNode; - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - - export function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - - export function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode) { - const typePredicateNode = createSynthesizedNode(SyntaxKind.TypePredicate) as TypePredicateNode; - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - - export function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - - export function createTypeQueryNode(exprName: EntityName) { - const typeQueryNode = createSynthesizedNode(SyntaxKind.TypeQuery) as TypeQueryNode; - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - - export function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - - export function createArrayTypeNode(elementType: TypeNode) { - const arrayTypeNode = createSynthesizedNode(SyntaxKind.ArrayType) as ArrayTypeNode; - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - - export function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - - export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode; - export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode; - export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode; - export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]) { - const unionTypeNode = createSynthesizedNode(kind) as UnionTypeNode | IntersectionTypeNode; - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - - export function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - - export function createParenthesizedType(type: TypeNode) { - const node = createSynthesizedNode(SyntaxKind.ParenthesizedType); - node.type = type; - return node; - } - - export function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - - export function createTypeLiteralNode(members: TypeElement[]) { - const typeLiteralNode = createSynthesizedNode(SyntaxKind.TypeLiteral) as TypeLiteralNode; - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - - export function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - - export function createTupleTypeNode(elementTypes: TypeNode[]) { - const tupleTypeNode = createSynthesizedNode(SyntaxKind.TupleType) as TupleTypeNode; - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - - export function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - - export function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode { - const mappedTypeNode = createSynthesizedNode(SyntaxKind.MappedType) as MappedTypeNode; - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - - export function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - - export function createTypeOperatorNode(type: TypeNode) { - const typeOperatorNode = createSynthesizedNode(SyntaxKind.TypeOperator) as TypeOperatorNode; - typeOperatorNode.operator = SyntaxKind.KeyOfKeyword; - typeOperatorNode.type = type; - return typeOperatorNode; - } - - export function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - - export function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode) { - const indexedAccessTypeNode = createSynthesizedNode(SyntaxKind.IndexedAccessType) as IndexedAccessTypeNode; - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - - export function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - - // Type Declarations + // Signature elements export function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined) { - const typeParameter = createSynthesizedNode(SyntaxKind.TypeParameter) as TypeParameterDeclaration; - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - - return typeParameter; + const node = createSynthesizedNode(SyntaxKind.TypeParameter) as TypeParameterDeclaration; + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } export function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined) { @@ -466,46 +244,6 @@ namespace ts { : node; } - // Signature elements - - export function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature { - const propertySignature = createSynthesizedNode(SyntaxKind.PropertySignature) as PropertySignature; - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - - export function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - - export function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration { - const indexSignature = createSynthesizedNode(SyntaxKind.IndexSignature) as IndexSignatureDeclaration; - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - - export function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - - // Signature elements - export function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression) { const node = createSynthesizedNode(SyntaxKind.Parameter); node.decorators = asNodeArray(decorators); @@ -542,7 +280,28 @@ namespace ts { : node; } - // Type members + + // Type Elements + + export function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature { + const node = createSynthesizedNode(SyntaxKind.PropertySignature) as PropertySignature; + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + + export function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } export function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression) { const node = createSynthesizedNode(SyntaxKind.PropertyDeclaration); @@ -565,7 +324,24 @@ namespace ts { : node; } - export function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) { + export function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined) { + const node = createSignatureDeclaration(SyntaxKind.MethodSignature, typeParameters, parameters, type) as MethodSignature; + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + + export function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + + export function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) { const node = createSynthesizedNode(SyntaxKind.MethodDeclaration); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -588,7 +364,7 @@ namespace ts { || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } @@ -656,6 +432,254 @@ namespace ts { : node; } + export function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { + return createSignatureDeclaration(SyntaxKind.CallSignature, typeParameters, parameters, type) as CallSignatureDeclaration; + } + + export function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + + export function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { + return createSignatureDeclaration(SyntaxKind.ConstructSignature, typeParameters, parameters, type) as ConstructSignatureDeclaration; + } + + export function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + + export function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration { + const node = createSynthesizedNode(SyntaxKind.IndexSignature) as IndexSignatureDeclaration; + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + + export function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + + /* @internal */ + export function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { + const node = createSynthesizedNode(kind) as SignatureDeclaration; + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + + function updateSignatureDeclaration(node: T, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): T { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + + // Types + + export function createKeywordTypeNode(kind: KeywordTypeNode["kind"]) { + return createSynthesizedNode(kind); + } + + export function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode) { + const node = createSynthesizedNode(SyntaxKind.TypePredicate) as TypePredicateNode; + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + + export function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + + export function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined) { + const node = createSynthesizedNode(SyntaxKind.TypeReference) as TypeReferenceNode; + node.typeName = asName(typeName); + node.typeArguments = typeArguments && parenthesizeTypeParameters(typeArguments); + return node; + } + + export function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + + export function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { + return createSignatureDeclaration(SyntaxKind.FunctionType, typeParameters, parameters, type) as FunctionTypeNode; + } + + export function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + + export function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { + return createSignatureDeclaration(SyntaxKind.ConstructorType, typeParameters, parameters, type) as ConstructorTypeNode; + } + + export function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + + export function createTypeQueryNode(exprName: EntityName) { + const node = createSynthesizedNode(SyntaxKind.TypeQuery) as TypeQueryNode; + node.exprName = exprName; + return node; + } + + export function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + + export function createTypeLiteralNode(members: TypeElement[]) { + const node = createSynthesizedNode(SyntaxKind.TypeLiteral) as TypeLiteralNode; + node.members = createNodeArray(members); + return node; + } + + export function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + + export function createArrayTypeNode(elementType: TypeNode) { + const node = createSynthesizedNode(SyntaxKind.ArrayType) as ArrayTypeNode; + node.elementType = parenthesizeElementTypeMember(elementType); + return node; + } + + export function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + + export function createTupleTypeNode(elementTypes: TypeNode[]) { + const node = createSynthesizedNode(SyntaxKind.TupleType) as TupleTypeNode; + node.elementTypes = createNodeArray(elementTypes); + return node; + } + + export function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + + export function createUnionTypeNode(types: TypeNode[]): UnionTypeNode { + return createUnionOrIntersectionTypeNode(SyntaxKind.UnionType, types); + } + + export function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray) { + return updateUnionOrIntersectionTypeNode(node, types); + } + + export function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode { + return createUnionOrIntersectionTypeNode(SyntaxKind.IntersectionType, types); + } + + export function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray) { + return updateUnionOrIntersectionTypeNode(node, types); + } + + export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]) { + const node = createSynthesizedNode(kind) as UnionTypeNode | IntersectionTypeNode; + node.types = parenthesizeElementTypeMembers(types); + return node; + } + + function updateUnionOrIntersectionTypeNode(node: T, types: NodeArray): T { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + + export function createParenthesizedType(type: TypeNode) { + const node = createSynthesizedNode(SyntaxKind.ParenthesizedType); + node.type = type; + return node; + } + + export function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + + export function createThisTypeNode() { + return createSynthesizedNode(SyntaxKind.ThisType); + } + + export function createTypeOperatorNode(type: TypeNode) { + const node = createSynthesizedNode(SyntaxKind.TypeOperator) as TypeOperatorNode; + node.operator = SyntaxKind.KeyOfKeyword; + node.type = parenthesizeElementTypeMember(type); + return node; + } + + export function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + + export function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode) { + const node = createSynthesizedNode(SyntaxKind.IndexedAccessType) as IndexedAccessTypeNode; + node.objectType = parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + + export function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + + export function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode { + const node = createSynthesizedNode(SyntaxKind.MappedType) as MappedTypeNode; + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + + export function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + + export function createLiteralTypeNode(literal: Expression) { + const node = createSynthesizedNode(SyntaxKind.LiteralType) as LiteralTypeNode; + node.literal = literal; + return node; + } + + export function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + // Binding Patterns export function createObjectBindingPattern(elements: BindingElement[]) { @@ -705,10 +729,7 @@ namespace ts { export function createArrayLiteral(elements?: Expression[], multiLine?: boolean) { const node = createSynthesizedNode(SyntaxKind.ArrayLiteralExpression); node.elements = parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { - node.multiLine = true; - } - + if (multiLine) node.multiLine = true; return node; } @@ -721,9 +742,7 @@ namespace ts { export function createObjectLiteral(properties?: ObjectLiteralElementLike[], multiLine?: boolean) { const node = createSynthesizedNode(SyntaxKind.ObjectLiteralExpression); node.properties = createNodeArray(properties); - if (multiLine) { - node.multiLine = true; - } + if (multiLine) node.multiLine = true; return node; } @@ -773,9 +792,9 @@ namespace ts { } export function updateCall(node: CallExpression, expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[]) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -965,10 +984,10 @@ namespace ts { return node; } - export function updateBinary(node: BinaryExpression, left: Expression, right: Expression) { + export function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } @@ -1099,6 +1118,19 @@ namespace ts { : node; } + export function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier) { + const node = createSynthesizedNode(SyntaxKind.MetaProperty); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + + export function updateMetaProperty(node: MetaProperty, name: Identifier) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + // Misc export function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail) { @@ -1115,6 +1147,10 @@ namespace ts { : node; } + export function createSemicolonClassElement() { + return createSynthesizedNode(SyntaxKind.SemicolonClassElement); + } + // Element export function createBlock(statements: Statement[], multiLine?: boolean): Block { @@ -1125,7 +1161,7 @@ namespace ts { } export function updateBlock(node: Block, statements: Statement[]) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -1145,35 +1181,6 @@ namespace ts { : node; } - export function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags) { - const node = createSynthesizedNode(SyntaxKind.VariableDeclarationList); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - - export function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - - export function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression) { - const node = createSynthesizedNode(SyntaxKind.VariableDeclaration); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; - return node; - } - - export function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - export function createEmptyStatement() { return createSynthesizedNode(SyntaxKind.EmptyStatement); } @@ -1392,6 +1399,39 @@ namespace ts { : node; } + export function createDebuggerStatement() { + return createSynthesizedNode(SyntaxKind.DebuggerStatement); + } + + export function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression) { + const node = createSynthesizedNode(SyntaxKind.VariableDeclaration); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + + export function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + + export function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags) { + const node = createSynthesizedNode(SyntaxKind.VariableDeclarationList); + node.flags |= flags & NodeFlags.BlockScoped; + node.declarations = createNodeArray(declarations); + return node; + } + + export function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + export function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) { const node = createSynthesizedNode(SyntaxKind.FunctionDeclaration); node.decorators = asNodeArray(decorators); @@ -1462,19 +1502,23 @@ namespace ts { : node; } - export function createTypeAliasDeclaration(name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) { + export function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) { const node = createSynthesizedNode(SyntaxKind.TypeAliasDeclaration); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.typeParameters = asNodeArray(typeParameters); node.type = type; return node; } - export function updateTypeAliasDeclaration(node: TypeAliasDeclaration, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) { - return node.name !== name + export function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name || node.typeParameters !== typeParameters || node.type !== type - ? updateNode(createTypeAliasDeclaration(name, typeParameters, type), node) + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) : node; } @@ -1498,7 +1542,7 @@ namespace ts { export function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags) { const node = createSynthesizedNode(SyntaxKind.ModuleDeclaration); - node.flags |= flags; + node.flags |= flags & (NodeFlags.Namespace | NodeFlags.NestedNamespace | NodeFlags.GlobalAugmentation); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -1539,6 +1583,18 @@ namespace ts { : node; } + export function createNamespaceExportDeclaration(name: string | Identifier) { + const node = createSynthesizedNode(SyntaxKind.NamespaceExportDeclaration); + node.name = asName(name); + return node; + } + + export function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + export function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference) { const node = createSynthesizedNode(SyntaxKind.ImportEqualsDeclaration); node.decorators = asNodeArray(decorators); @@ -1569,19 +1625,20 @@ namespace ts { export function updateImportDeclaration(node: ImportDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } - export function createImportClause(name: Identifier, namedBindings: NamedImportBindings): ImportClause { + export function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause { const node = createSynthesizedNode(SyntaxKind.ImportClause); node.name = name; node.namedBindings = namedBindings; return node; } - export function updateImportClause(node: ImportClause, name: Identifier, namedBindings: NamedImportBindings) { + export function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined) { return node.name !== name || node.namedBindings !== namedBindings ? updateNode(createImportClause(name, namedBindings), node) @@ -1759,19 +1816,6 @@ namespace ts { : node; } - export function createJsxAttributes(properties: JsxAttributeLike[]) { - const jsxAttributes = createSynthesizedNode(SyntaxKind.JsxAttributes); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - - export function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - export function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression) { const node = createSynthesizedNode(SyntaxKind.JsxAttribute); node.name = name; @@ -1786,6 +1830,18 @@ namespace ts { : node; } + export function createJsxAttributes(properties: JsxAttributeLike[]) { + const node = createSynthesizedNode(SyntaxKind.JsxAttributes); + node.properties = createNodeArray(properties); + return node; + } + + export function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + export function createJsxSpreadAttribute(expression: Expression) { const node = createSynthesizedNode(SyntaxKind.JsxSpreadAttribute); node.expression = expression; @@ -1813,20 +1869,6 @@ namespace ts { // Clauses - export function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]) { - const node = createSynthesizedNode(SyntaxKind.HeritageClause); - node.token = token; - node.types = createNodeArray(types); - return node; - } - - export function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - export function createCaseClause(expression: Expression, statements: Statement[]) { const node = createSynthesizedNode(SyntaxKind.CaseClause); node.expression = parenthesizeExpressionForList(expression); @@ -1835,10 +1877,10 @@ namespace ts { } export function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } export function createDefaultClause(statements: Statement[]) { @@ -1848,12 +1890,24 @@ namespace ts { } export function updateDefaultClause(node: DefaultClause, statements: Statement[]) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; + } + + export function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]) { + const node = createSynthesizedNode(SyntaxKind.HeritageClause); + node.token = token; + node.types = createNodeArray(types); return node; } + export function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + export function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block) { const node = createSynthesizedNode(SyntaxKind.CatchClause); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -1862,10 +1916,10 @@ namespace ts { } export function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } // Property assignments @@ -1879,10 +1933,10 @@ namespace ts { } export function updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } export function createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer?: Expression) { @@ -1893,10 +1947,10 @@ namespace ts { } export function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression | undefined) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } export function createSpreadAssignment(expression: Expression) { @@ -1906,10 +1960,9 @@ namespace ts { } export function updateSpreadAssignment(node: SpreadAssignment, expression: Expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } // Enum @@ -2042,6 +2095,30 @@ namespace ts { return node; } + function flattenCommaElements(node: Expression): Expression | Expression[] { + if (nodeIsSynthesized(node) && !isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === SyntaxKind.CommaListExpression) { + return (node).elements; + } + if (isBinaryExpression(node) && node.operatorToken.kind === SyntaxKind.CommaToken) { + return [node.left, node.right]; + } + } + return node; + } + + export function createCommaList(elements: Expression[]) { + const node = createSynthesizedNode(SyntaxKind.CommaListExpression); + node.elements = createNodeArray(sameFlatMap(elements, flattenCommaElements)); + return node; + } + + export function updateCommaList(node: CommaListExpression, elements: Expression[]) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + export function createBundle(sourceFiles: SourceFile[]) { const node = createNode(SyntaxKind.Bundle); node.sourceFiles = sourceFiles; @@ -2298,7 +2375,7 @@ namespace ts { /** * Sets the constant value to emit for an expression. */ - export function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number) { + export function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number) { const emitNode = getOrCreateEmitNode(node); emitNode.constantValue = value; return node; @@ -2430,6 +2507,25 @@ namespace ts { /* @internal */ namespace ts { + export const nullTransformationContext: TransformationContext = { + enableEmitNotification: noop, + enableSubstitution: noop, + endLexicalEnvironment: () => undefined, + getCompilerOptions: notImplemented, + getEmitHost: notImplemented, + getEmitResolver: notImplemented, + hoistFunctionDeclaration: noop, + hoistVariableDeclaration: noop, + isEmitNotificationEnabled: notImplemented, + isSubstitutionEnabled: notImplemented, + onEmitNode: noop, + onSubstituteNode: notImplemented, + readEmitHelpers: notImplemented, + requestEmitHelper: noop, + resumeLexicalEnvironment: noop, + startLexicalEnvironment: noop, + suspendLexicalEnvironment: noop + }; // Compound nodes @@ -2830,7 +2926,11 @@ namespace ts { } export function inlineExpressions(expressions: Expression[]) { - return reduceLeft(expressions, createComma); + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. + return expressions.length > 10 + ? createCommaList(expressions) + : reduceLeft(expressions, createComma); } export function createExpressionFromEntityName(node: EntityName | Expression): Expression { @@ -3064,9 +3164,10 @@ namespace ts { } function getName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags?: EmitFlags) { - if (node.name && isIdentifier(node.name) && !isGeneratedIdentifier(node.name)) { - const name = getMutableClone(node.name); - emitFlags |= getEmitFlags(node.name); + const nodeName = getNameOfDeclaration(node); + if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { + const name = getMutableClone(nodeName); + emitFlags |= getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= EmitFlags.NoSourceMap; if (!allowComments) emitFlags |= EmitFlags.NoComments; if (emitFlags) setEmitFlags(name, emitFlags); @@ -3225,16 +3326,6 @@ namespace ts { return statements; } - export function parenthesizeConditionalHead(condition: Expression) { - const conditionalPrecedence = getOperatorPrecedence(SyntaxKind.ConditionalExpression, SyntaxKind.QuestionToken); - const emittedCondition = skipPartiallyEmittedExpressions(condition); - const conditionPrecedence = getExpressionPrecedence(emittedCondition); - if (compareValues(conditionPrecedence, conditionalPrecedence) === Comparison.LessThan) { - return createParen(condition); - } - return condition; - } - /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -3536,6 +3627,35 @@ namespace ts { return expression; } + export function parenthesizeElementTypeMember(member: TypeNode) { + switch (member.kind) { + case SyntaxKind.UnionType: + case SyntaxKind.IntersectionType: + case SyntaxKind.FunctionType: + case SyntaxKind.ConstructorType: + return createParenthesizedType(member); + } + return member; + } + + export function parenthesizeElementTypeMembers(members: TypeNode[]) { + return createNodeArray(sameMap(members, parenthesizeElementTypeMember)); + } + + export function parenthesizeTypeParameters(typeParameters: TypeNode[]) { + if (some(typeParameters)) { + const nodeArray = createNodeArray() as NodeArray; + for (let i = 0; i < typeParameters.length; ++i) { + const entry = typeParameters[i]; + nodeArray.push(i === 0 && isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + createParenthesizedType(entry) : + entry); + } + + return nodeArray; + } + } + /** * Clones a series of not-emitted expressions with a new inner expression. * @@ -3742,7 +3862,7 @@ namespace ts { if (file.moduleName) { return createLiteral(file.moduleName); } - if (!isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return createLiteral(getExternalModuleNameFromPath(host, file.fileName)); } return undefined; diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index d511b31b331..4c6616c36d4 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -2,7 +2,6 @@ /// namespace ts { - /* @internal */ export function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; export function trace(host: ModuleResolutionHost): void { @@ -15,6 +14,7 @@ namespace ts { } /** Array that is only intended to be pushed to, never read. */ + /* @internal */ export interface Push { push(value: T): void; } @@ -47,13 +47,11 @@ namespace ts { return resolved.path; } - /** Adds `isExernalLibraryImport` to a Resolved to get a ResolvedModule. */ - function resolvedModuleFromResolved({ path, extension }: Resolved, isExternalLibraryImport: boolean): ResolvedModuleFull { - return { resolvedFileName: path, extension, isExternalLibraryImport }; - } - function createResolvedModuleWithFailedLookupLocations(resolved: Resolved | undefined, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport }, + failedLookupLocations + }; } export function moduleHasNonRelativeName(moduleName: string): boolean { @@ -442,6 +440,8 @@ namespace ts { case ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`); } if (perFolderCache) { @@ -653,11 +653,13 @@ namespace ts { if (state.traceEnabled) { trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); } - // A path mapping may have a ".ts" extension; in contrast to an import, which should omit it. - const tsExtension = tryGetExtensionFromPath(candidate); - if (tsExtension !== undefined) { + // A path mapping may have an extension, in contrast to an import, which should omit it. + const extension = tryGetExtensionFromPath(candidate); + if (extension !== undefined) { const path = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - return path && { path, extension: tsExtension }; + if (path !== undefined) { + return { path, extension }; + } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); @@ -675,12 +677,25 @@ namespace ts { } export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, /*jsOnly*/ false); + return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); } + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ /* @internal */ - export function nodeModuleNameResolverWorker(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, jsOnly = false): ResolvedModuleWithFailedLookupLocations { - const containingDirectory = getDirectoryPath(containingFile); + export function resolveJavaScriptModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string { + const { resolvedModule, failedLookupLocations } = + nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + if (!resolvedModule) { + throw new Error(`Could not resolve JS module ${moduleName} starting at ${initialDir}. Looked in: ${failedLookupLocations.join(", ")}`); + } + return resolvedModule.resolvedFileName; + } + + function nodeModuleNameResolverWorker(moduleName: string, containingDirectory: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache: ModuleResolutionCache | undefined, jsOnly: boolean): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; @@ -958,10 +973,13 @@ namespace ts { } } + /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ + const mangledScopedPackageSeparator = "__"; + /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ function mangleScopedPackage(moduleName: string, state: ModuleResolutionState): string { if (startsWith(moduleName, "@")) { - const replaceSlash = moduleName.replace(ts.directorySeparator, "__"); + const replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== moduleName) { const mangled = replaceSlash.slice(1); // Take off the "@" if (state.traceEnabled) { @@ -973,6 +991,17 @@ namespace ts { return moduleName; } + /* @internal */ + export function getPackageNameFromAtTypesDirectory(mangledName: string): string { + const withoutAtTypePrefix = removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return withoutAtTypePrefix.indexOf("__") !== -1 ? + "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + withoutAtTypePrefix; + } + return mangledName; + } + function tryFindNonRelativeModuleNameInCache(cache: PerModuleNameCache | undefined, moduleName: string, containingDirectory: string, traceEnabled: boolean, host: ModuleResolutionHost): SearchResult { const result = cache && cache.get(containingDirectory); if (result) { diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 834669169f5..58270627d49 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -23,19 +23,19 @@ namespace ts { } } - function visitNode(cbNode: (node: Node) => T, node: Node): T { + function visitNode(cbNode: (node: Node) => T, node?: Node): T | undefined { if (node) { return cbNode(node); } } - function visitNodeArray(cbNodes: (nodes: Node[]) => T, nodes: Node[]) { + function visitNodeArray(cbNodes: (nodes: Node[]) => T, nodes?: Node[]): T | undefined { if (nodes) { return cbNodes(nodes); } } - function visitEachNode(cbNode: (node: Node) => T, nodes: Node[]) { + function visitEachNode(cbNode: (node: Node) => T, nodes?: Node[]): T | undefined { if (nodes) { for (const node of nodes) { const result = cbNode(node); @@ -56,14 +56,14 @@ namespace ts { * @param cbNode a callback to be invoked for all child nodes * @param cbNodeArray a callback to be invoked for embedded array */ - export function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T { + export function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined { if (!node) { return; } // The visitXXX functions could be written as local functions that close over the cbNode and cbNodeArray // callback parameters, but that causes a closure allocation for each invocation with noticeable effects // on performance. - const visitNodes: (cb: ((node: Node) => T) | ((node: Node[]) => T), nodes: Node[]) => T = cbNodeArray ? visitNodeArray : visitEachNode; + const visitNodes: (cb: ((node?: Node) => T | undefined) | ((node?: Node[]) => T | undefined), nodes?: Node[]) => T | undefined = cbNodeArray ? visitNodeArray : visitEachNode; const cbNodes = cbNodeArray || cbNode; switch (node.kind) { case SyntaxKind.QualifiedName: @@ -368,6 +368,8 @@ namespace ts { return visitNode(cbNode, (node).expression); case SyntaxKind.MissingDeclaration: return visitNodes(cbNodes, node.decorators); + case SyntaxKind.CommaListExpression: + return visitNodes(cbNodes, (node).elements); case SyntaxKind.JsxElement: return visitNode(cbNode, (node).openingElement) || @@ -1244,12 +1246,12 @@ namespace ts { if (token() === SyntaxKind.ExportKeyword) { nextToken(); if (token() === SyntaxKind.DefaultKeyword) { - return lookAhead(nextTokenIsClassOrFunctionOrAsync); + return lookAhead(nextTokenCanFollowDefaultKeyword); } return token() !== SyntaxKind.AsteriskToken && token() !== SyntaxKind.AsKeyword && token() !== SyntaxKind.OpenBraceToken && canFollowModifier(); } if (token() === SyntaxKind.DefaultKeyword) { - return nextTokenIsClassOrFunctionOrAsync(); + return nextTokenCanFollowDefaultKeyword(); } if (token() === SyntaxKind.StaticKeyword) { nextToken(); @@ -1271,9 +1273,10 @@ namespace ts { || isLiteralPropertyName(); } - function nextTokenIsClassOrFunctionOrAsync(): boolean { + function nextTokenCanFollowDefaultKeyword(): boolean { nextToken(); return token() === SyntaxKind.ClassKeyword || token() === SyntaxKind.FunctionKeyword || + token() === SyntaxKind.InterfaceKeyword || (token() === SyntaxKind.AbstractKeyword && lookAhead(nextTokenIsClassKeywordOnSameLine)) || (token() === SyntaxKind.AsyncKeyword && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } @@ -6519,6 +6522,8 @@ namespace ts { case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 646bfc49818..61a1e0ba246 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -241,6 +241,101 @@ namespace ts { return output; } + const redForegroundEscapeSequence = "\u001b[91m"; + const yellowForegroundEscapeSequence = "\u001b[93m"; + const blueForegroundEscapeSequence = "\u001b[93m"; + const gutterStyleSequence = "\u001b[100;30m"; + const gutterSeparator = " "; + const resetEscapeSequence = "\u001b[0m"; + const ellipsis = "..."; + function getCategoryFormat(category: DiagnosticCategory): string { + switch (category) { + case DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case DiagnosticCategory.Error: return redForegroundEscapeSequence; + case DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + + function formatAndReset(text: string, formatStyle: string) { + return formatStyle + text + resetEscapeSequence; + } + + function padLeft(s: string, length: number) { + while (s.length < length) { + s = " " + s; + } + return s; + } + + export function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string { + let output = ""; + for (const diagnostic of diagnostics) { + if (diagnostic.file) { + const { start, length, file } = diagnostic; + const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); + const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length); + const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line; + const relativeFileName = host ? convertToRelativePath(file.fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName)) : file.fileName; + + const hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + let gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + + output += sys.newLine; + for (let i = firstLine; i <= lastLine; i++) { + // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, + // so we'll skip ahead to the second-to-last line. + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + sys.newLine; + i = lastLine - 1; + } + + const lineStart = getPositionOfLineAndCharacter(file, i, 0); + const lineEnd = i < lastLineInFile ? getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + let lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + + // Output the gutter and the actual contents of the line. + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + sys.newLine; + + // Output the gutter and the error span for the line using tildes. + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + const lastCharForLine = i === lastLine ? lastLineChar : undefined; + + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + + output += sys.newLine; + } + + output += sys.newLine; + output += `${ relativeFileName }(${ firstLine + 1 },${ firstLineChar + 1 }): `; + } + + const categoryColor = getCategoryFormat(diagnostic.category); + const category = DiagnosticCategory[diagnostic.category].toLowerCase(); + output += `${ formatAndReset(category, categoryColor) } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine) }`; + } + return output; + } + export function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string { if (typeof messageText === "string") { return messageText; @@ -291,6 +386,19 @@ namespace ts { allDiagnostics?: Diagnostic[]; } + /** + * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' + * that represent a compilation unit. + * + * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and + * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. + * + * @param rootNames - A set of root files. + * @param options - The compiler options which should be used. + * @param host - The host interacts with the underlying file system. + * @param oldProgram - Reuses an old program structure. + * @returns A 'Program' object. + */ export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program { let program: Program; let files: SourceFile[] = []; @@ -434,7 +542,8 @@ namespace ts { getFileProcessingDiagnostics: () => fileProcessingDiagnostics, getResolvedTypeReferenceDirectives: () => resolvedTypeReferenceDirectives, isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference, }; verifyCompilerOptions(); @@ -1214,7 +1323,7 @@ namespace ts { } function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { - return isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics(): Diagnostic[] { @@ -1253,7 +1362,6 @@ namespace ts { const isJavaScriptFile = isSourceFileJavaScript(file); const isExternalModuleFile = isExternalModule(file); - const isDtsFile = isDeclarationFile(file); // file.imports may not be undefined if there exists dynamic import let imports: LiteralExpression[]; @@ -1307,7 +1415,7 @@ namespace ts { } break; case SyntaxKind.ModuleDeclaration: - if (isAmbientModule(node) && (inAmbientModule || hasModifier(node, ModifierFlags.Ambient) || isDeclarationFile(file))) { + if (isAmbientModule(node) && (inAmbientModule || hasModifier(node, ModifierFlags.Ambient) || file.isDeclarationFile)) { const moduleName = (node).name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: @@ -1318,7 +1426,7 @@ namespace ts { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { // for global .d.ts files record name of ambient module (ambientModules || (ambientModules = [])).push(moduleName.text); } @@ -1353,48 +1461,60 @@ namespace ts { } } - function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) { - let diagnosticArgument: string[]; - let diagnostic: DiagnosticMessage; + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile: SourceFile, ref: FileReference): SourceFile | undefined { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), fileName => filesByName.get(toPath(fileName, currentDirectory, getCanonicalFileName))); + } + + function getSourceFileFromReferenceWorker( + fileName: string, + getSourceFile: (fileName: string) => SourceFile | undefined, + fail?: (diagnostic: DiagnosticMessage, ...argument: string[]) => void, + refFile?: SourceFile): SourceFile | undefined { + if (hasExtension(fileName)) { if (!options.allowNonTsExtensions && !forEach(supportedExtensions, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) { - diagnostic = Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) fail(Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; - } - } - else { - const nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!forEach(supportedExtensions, extension => findSourceFile(fileName + extension, toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd))) { - diagnostic = Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } - } - } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...diagnosticArgument)); + const sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } - else { - fileProcessingDiagnostics.add(createCompilerDiagnostic(diagnostic, ...diagnosticArgument)); + return sourceFile; + } else { + const sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) return sourceFileNoExtension; + + if (fail && options.allowNonTsExtensions) { + fail(Diagnostics.File_0_not_found, fileName); + return undefined; } + + const sourceFileWithAddedExtension = forEach(supportedExtensions, extension => getSourceFile(fileName + extension)); + if (fail && !sourceFileWithAddedExtension) fail(Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): void { + getSourceFileFromReferenceWorker(fileName, + fileName => findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd), + (diagnostic, ...args) => { + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...args) + : createCompilerDiagnostic(diagnostic, ...args)); + }, + refFile); + } + function reportFileNamesDifferOnlyInCasingError(fileName: string, existingFileName: string, refFile: SourceFile, refPos: number, refEnd: number): void { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, @@ -1640,7 +1760,7 @@ namespace ts { const absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (const sourceFile of sourceFiles) { - if (!isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -1753,13 +1873,13 @@ namespace ts { const languageVersion = options.target || ScriptTarget.ES3; const outFile = options.outFile || options.out; - const firstNonAmbientExternalModuleSourceFile = forEach(files, f => isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); + const firstNonAmbientExternalModuleSourceFile = forEach(files, f => isExternalModule(f) && !f.isDeclarationFile ? f : undefined); if (options.isolatedModules) { if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES2015) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); + const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !f.isDeclarationFile ? f : undefined); if (firstNonExternalModuleSourceFile) { const span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 659c2f416ab..d27bbf879fe 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -712,11 +712,11 @@ namespace ts { return accumulator; } - export function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T) { + export function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined { return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state); } - export function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T) { + export function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined { return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state); } @@ -746,10 +746,11 @@ namespace ts { } /** Optionally, get the shebang */ - export function getShebang(text: string): string { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + export function getShebang(text: string): string | undefined { + const match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } export function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean { diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index 618e626f463..cd5cc95e2e1 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -166,7 +166,7 @@ namespace ts { }; function transformRoot(node: T) { - return node && (!isSourceFile(node) || !isDeclarationFile(node)) ? transformation(node) : node; + return node && (!isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } /** diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 734fbcaeb16..63c10145165 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -295,7 +295,7 @@ namespace ts { return transformSourceFile; function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } @@ -2009,13 +2009,14 @@ namespace ts { } else { assignment = createBinary(decl.name, SyntaxKind.EqualsToken, visitNode(decl.initializer, visitor, isExpression)); + setTextRange(assignment, decl); } assignments = append(assignments, assignment); } } if (assignments) { - updated = setTextRange(createStatement(reduceLeft(assignments, (acc, v) => createBinary(v, SyntaxKind.CommaToken, acc))), node); + updated = setTextRange(createStatement(inlineExpressions(assignments)), node); } else { // none of declarations has initializer - the entire variable statement can be deleted @@ -3748,7 +3749,7 @@ namespace ts { case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.VariableDeclaration: - return (parent).name === node + return (parent).name === node && resolver.isDeclarationWithCollidingName(parent); } @@ -3781,7 +3782,7 @@ namespace ts { if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings && !isInternalName(node)) { const declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return setTextRange(getGeneratedNameForNode(declaration.name), node); + return setTextRange(getGeneratedNameForNode(getNameOfDeclaration(declaration)), node); } } diff --git a/src/compiler/transformers/es2016.ts b/src/compiler/transformers/es2016.ts index 1118e6ad9b6..a9468991776 100644 --- a/src/compiler/transformers/es2016.ts +++ b/src/compiler/transformers/es2016.ts @@ -9,7 +9,7 @@ namespace ts { return transformSourceFile; function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 3bbb3b3123f..3565547d78a 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -47,7 +47,7 @@ namespace ts { return transformSourceFile; function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 3aa5be551a6..6e2f70b5c35 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -33,7 +33,7 @@ namespace ts { return transformSourceFile; function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } @@ -106,15 +106,11 @@ namespace ts { } } - function visitAwaitExpression(node: AwaitExpression) { + function visitAwaitExpression(node: AwaitExpression): Expression { if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) { - const expression = visitNode(node.expression, visitor, isExpression); return setOriginalNode( setTextRange( - createYield( - /*asteriskToken*/ undefined, - createArrayLiteral([createLiteral("await"), expression]) - ), + createYield(createAwaitHelper(context, visitNode(node.expression, visitor, isExpression))), /*location*/ node ), node @@ -124,18 +120,26 @@ namespace ts { } function visitYieldExpression(node: YieldExpression) { - if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) { + if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator && node.asteriskToken) { const expression = visitNode(node.expression, visitor, isExpression); - return updateYield( - node, - node.asteriskToken, - node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : createArrayLiteral( - expression - ? [createLiteral("yield"), expression] - : [createLiteral("yield")] - ) + return setOriginalNode( + setTextRange( + createYield( + createAwaitHelper(context, + updateYield( + node, + node.asteriskToken, + createAsyncDelegatorHelper( + context, + createAsyncValuesHelper(context, expression, expression), + expression + ) + ) + ) + ), + node + ), + node ); } return visitEachChild(node, visitor, context); @@ -347,6 +351,10 @@ namespace ts { ); } + function awaitAsYield(expression: Expression) { + return createYield(/*asteriskToken*/ undefined, enclosingFunctionFlags & FunctionFlags.Generator ? createAwaitHelper(context, expression) : expression); + } + function transformForAwaitOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement) { const expression = visitNode(node.expression, visitor, isExpression); const iterator = isIdentifier(expression) ? getGeneratedNameForNode(expression) : createTempVariable(/*recordTempVariable*/ undefined); @@ -354,16 +362,11 @@ namespace ts { const errorRecord = createUniqueName("e"); const catchVariable = getGeneratedNameForNode(errorRecord); const returnMethod = createTempVariable(/*recordTempVariable*/ undefined); - const values = createAsyncValuesHelper(context, expression, /*location*/ node.expression); - const next = createYield( - /*asteriskToken*/ undefined, - enclosingFunctionFlags & FunctionFlags.Generator - ? createArrayLiteral([ - createLiteral("await"), - createCall(createPropertyAccess(iterator, "next" ), /*typeArguments*/ undefined, []) - ]) - : createCall(createPropertyAccess(iterator, "next" ), /*typeArguments*/ undefined, []) - ); + const callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + const callNext = createCall(createPropertyAccess(iterator, "next" ), /*typeArguments*/ undefined, []); + const getDone = createPropertyAccess(result, "done"); + const getValue = createPropertyAccess(result, "value"); + const callReturn = createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); @@ -374,16 +377,19 @@ namespace ts { /*initializer*/ setEmitFlags( setTextRange( createVariableDeclarationList([ - setTextRange(createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), - createVariableDeclaration(result, /*type*/ undefined, next) + setTextRange(createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + createVariableDeclaration(result) ]), node.expression ), EmitFlags.NoHoisting ), - /*condition*/ createLogicalNot(createPropertyAccess(result, "done")), - /*incrementor*/ createAssignment(result, next), - /*statement*/ convertForOfStatementHead(node, createPropertyAccess(result, "value")) + /*condition*/ createComma( + createAssignment(result, awaitAsYield(callNext)), + createLogicalNot(getDone) + ), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue)) ), /*location*/ node ), @@ -421,26 +427,14 @@ namespace ts { createLogicalAnd( createLogicalAnd( result, - createLogicalNot( - createPropertyAccess(result, "done") - ) + createLogicalNot(getDone) ), createAssignment( returnMethod, createPropertyAccess(iterator, "return") ) ), - createStatement( - createYield( - /*asteriskToken*/ undefined, - enclosingFunctionFlags & FunctionFlags.Generator - ? createArrayLiteral([ - createLiteral("await"), - createFunctionCall(returnMethod, iterator, []) - ]) - : createFunctionCall(returnMethod, iterator, []) - ) - ) + createStatement(awaitAsYield(callReturn)) ), EmitFlags.SingleLine ) @@ -880,27 +874,39 @@ namespace ts { ); } + const awaitHelper: EmitHelper = { + name: "typescript:await", + scoped: false, + text: ` + var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } + ` + }; + + function createAwaitHelper(context: TransformationContext, expression: Expression) { + context.requestEmitHelper(awaitHelper); + return createCall(getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } + const asyncGeneratorHelper: EmitHelper = { name: "typescript:asyncGenerator", scoped: false, text: ` var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; ` }; function createAsyncGeneratorHelper(context: TransformationContext, generatorFunc: FunctionExpression) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); // Mark this node as originally an async function @@ -922,16 +928,16 @@ namespace ts { scoped: false, text: ` var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; ` }; function createAsyncDelegatorHelper(context: TransformationContext, expression: Expression, location?: TextRange) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return setTextRange( createCall( getHelperName("__asyncDelegator"), diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index 286892f9d3b..9aadd6bc686 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -293,8 +293,7 @@ namespace ts { return transformSourceFile; function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node) - || (node.transformFlags & TransformFlags.ContainsGenerator) === 0) { + if (node.isDeclarationFile || (node.transformFlags & TransformFlags.ContainsGenerator) === 0) { return node; } diff --git a/src/compiler/transformers/jsx.ts b/src/compiler/transformers/jsx.ts index e9455490a5d..09f361d1b13 100644 --- a/src/compiler/transformers/jsx.ts +++ b/src/compiler/transformers/jsx.ts @@ -15,7 +15,7 @@ namespace ts { * @param node A SourceFile node. */ function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } diff --git a/src/compiler/transformers/module/es2015.ts b/src/compiler/transformers/module/es2015.ts index 660293e074f..3951d08109d 100644 --- a/src/compiler/transformers/module/es2015.ts +++ b/src/compiler/transformers/module/es2015.ts @@ -16,7 +16,7 @@ namespace ts { return transformSourceFile; function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index 70e85cfa678..d81265a569f 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -56,7 +56,7 @@ namespace ts { * @param node The SourceFile node. */ function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node) || !(isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & TransformFlags.ContainsDynamicImport)) { + if (node.isDeclarationFile || !(isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & TransformFlags.ContainsDynamicImport)) { return node; } diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index e79dd1abbd8..8e7f0ae30d9 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -50,7 +50,7 @@ namespace ts { * @param node The SourceFile node. */ function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node) || !(isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & TransformFlags.ContainsDynamicImport)) { + if (node.isDeclarationFile || !(isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & TransformFlags.ContainsDynamicImport)) { return node; } diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 555855b5e23..d02aaecf333 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -76,7 +76,7 @@ namespace ts { * @param node A SourceFile node. */ function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } @@ -345,6 +345,9 @@ namespace ts { case SyntaxKind.PropertyDeclaration: // TypeScript property declarations are elided. + + case SyntaxKind.NamespaceExportDeclaration: + // TypeScript namespace export declarations are elided. return undefined; case SyntaxKind.Constructor: @@ -1762,23 +1765,19 @@ namespace ts { } function serializeUnionOrIntersectionType(node: UnionOrIntersectionTypeNode): SerializedTypeNode { + // Note when updating logic here also update getEntityNameForDecoratorMetadata + // so that aliases can be marked as referenced let serializedUnion: SerializedTypeNode; for (const typeNode of node.types) { const serializedIndividual = serializeTypeNode(typeNode); - if (isVoidExpression(serializedIndividual)) { - // If we dont have any other type already set, set the initial type - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { // One of the individual is global object, return immediately return serializedIndividual; } // If there exists union that is not void 0 expression, check if the the common type is identifier. // anything more complex and we will just default to Object - else if (serializedUnion && !isVoidExpression(serializedUnion)) { + else if (serializedUnion) { // Different types if (!isIdentifier(serializedUnion) || !isIdentifier(serializedIndividual) || @@ -2498,22 +2497,27 @@ namespace ts { // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes // old emitter always generate 'expression' part of the name as-is. const name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); + const valueExpression = transformEnumMemberDeclarationValue(member); + const innerAssignment = createAssignment( + createElementAccess( + currentNamespaceContainerName, + name + ), + valueExpression + ); + const outerAssignment = valueExpression.kind === SyntaxKind.StringLiteral ? + innerAssignment : + createAssignment( + createElementAccess( + currentNamespaceContainerName, + innerAssignment + ), + name + ); return setTextRange( createStatement( setTextRange( - createAssignment( - createElementAccess( - currentNamespaceContainerName, - createAssignment( - createElementAccess( - currentNamespaceContainerName, - name - ), - transformEnumMemberDeclarationValue(member) - ) - ), - name - ), + outerAssignment, member ) ), @@ -2922,7 +2926,7 @@ namespace ts { function visitExportDeclaration(node: ExportDeclaration): VisitResult { if (!node.exportClause) { // Elide a star export if the module it references does not export a value. - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { @@ -3353,7 +3357,7 @@ namespace ts { return node; } - function tryGetConstEnumValue(node: Node): number { + function tryGetConstEnumValue(node: Node): string | number { if (compilerOptions.isolatedModules) { return undefined; } diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index 8981da65ba3..834c7326e22 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -60,93 +60,8 @@ namespace ts { sys.write(ts.formatDiagnostics([diagnostic], host)); } - const redForegroundEscapeSequence = "\u001b[91m"; - const yellowForegroundEscapeSequence = "\u001b[93m"; - const blueForegroundEscapeSequence = "\u001b[93m"; - const gutterStyleSequence = "\u001b[100;30m"; - const gutterSeparator = " "; - const resetEscapeSequence = "\u001b[0m"; - const ellipsis = "..."; - function getCategoryFormat(category: DiagnosticCategory): string { - switch (category) { - case DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; - case DiagnosticCategory.Error: return redForegroundEscapeSequence; - case DiagnosticCategory.Message: return blueForegroundEscapeSequence; - } - } - - function formatAndReset(text: string, formatStyle: string) { - return formatStyle + text + resetEscapeSequence; - } - function reportDiagnosticWithColorAndContext(diagnostic: Diagnostic, host: FormatDiagnosticsHost): void { - let output = ""; - - if (diagnostic.file) { - const { start, length, file } = diagnostic; - const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); - const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length); - const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line; - const relativeFileName = host ? convertToRelativePath(file.fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName)) : file.fileName; - - const hasMoreThanFiveLines = (lastLine - firstLine) >= 4; - let gutterWidth = (lastLine + 1 + "").length; - if (hasMoreThanFiveLines) { - gutterWidth = Math.max(ellipsis.length, gutterWidth); - } - - output += sys.newLine; - for (let i = firstLine; i <= lastLine; i++) { - // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, - // so we'll skip ahead to the second-to-last line. - if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + sys.newLine; - i = lastLine - 1; - } - - const lineStart = getPositionOfLineAndCharacter(file, i, 0); - const lineEnd = i < lastLineInFile ? getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; - let lineContent = file.text.slice(lineStart, lineEnd); - lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces - - // Output the gutter and the actual contents of the line. - output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + sys.newLine; - - // Output the gutter and the error span for the line using tildes. - output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += redForegroundEscapeSequence; - if (i === firstLine) { - // If we're on the last line, then limit it to the last character of the last line. - // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. - const lastCharForLine = i === lastLine ? lastLineChar : undefined; - - output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); - } - else if (i === lastLine) { - output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); - } - else { - // Squiggle the entire line. - output += lineContent.replace(/./g, "~"); - } - output += resetEscapeSequence; - - output += sys.newLine; - } - - output += sys.newLine; - output += `${ relativeFileName }(${ firstLine + 1 },${ firstLineChar + 1 }): `; - } - - const categoryColor = getCategoryFormat(diagnostic.category); - const category = DiagnosticCategory[diagnostic.category].toLowerCase(); - output += `${ formatAndReset(category, categoryColor) } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine) }`; - output += sys.newLine + sys.newLine; - - sys.write(output); + sys.write(ts.formatDiagnosticsWithColorAndContext([diagnostic], host) + sys.newLine + sys.newLine); } function reportWatchDiagnostic(diagnostic: Diagnostic) { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 8c134f79333..b2d4878a415 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -389,6 +389,7 @@ namespace ts { // Transformation nodes NotEmittedStatement, PartiallyEmittedExpression, + CommaListExpression, MergeDeclarationMarker, EndOfDeclarationMarker, @@ -580,11 +581,16 @@ namespace ts { export interface Identifier extends PrimaryExpression { kind: SyntaxKind.Identifier; - text: string; // Text of identifier (with escapes converted to characters) - originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later + /** + * Text of identifier (with escapes converted to characters). + * If the identifier begins with two underscores, this will begin with three. + */ + text: string; + originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later /*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier. - /*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name. - isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace + /*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name. + isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace + /*@internal*/ typeArguments?: NodeArray; // Only defined on synthesized nodes. Though not syntactically valid, used in emitting diagnostics. } // Transient identifier node (marked by id === -1) @@ -614,10 +620,13 @@ namespace ts { export interface Declaration extends Node { _declarationBrand: any; + } + + export interface NamedDeclaration extends Declaration { name?: DeclarationName; } - export interface DeclarationStatement extends Declaration, Statement { + export interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } @@ -631,7 +640,7 @@ namespace ts { expression: LeftHandSideExpression; } - export interface TypeParameterDeclaration extends Declaration { + export interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -642,7 +651,7 @@ namespace ts { expression?: Expression; } - export interface SignatureDeclaration extends Declaration { + export interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -659,7 +668,7 @@ namespace ts { export type BindingName = Identifier | BindingPattern; - export interface VariableDeclaration extends Declaration { + export interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; // Declared variable name @@ -673,7 +682,7 @@ namespace ts { declarations: NodeArray; } - export interface ParameterDeclaration extends Declaration { + export interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; // Present on rest parameter @@ -683,7 +692,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface BindingElement extends Declaration { + export interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; // Binding property name (in object binding pattern) @@ -708,7 +717,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface ObjectLiteralElement extends Declaration { + export interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -752,7 +761,7 @@ namespace ts { // SyntaxKind.ShorthandPropertyAssignment // SyntaxKind.EnumMember // SyntaxKind.JSDocPropertyTag - export interface VariableLikeDeclaration extends Declaration { + export interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -761,7 +770,7 @@ namespace ts { initializer?: Expression; } - export interface PropertyLikeDeclaration extends Declaration { + export interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } @@ -892,6 +901,8 @@ namespace ts { kind: SyntaxKind.ConstructorType; } + export type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference; + export interface TypeReferenceNode extends TypeNode { kind: SyntaxKind.TypeReference; typeName: EntityName; @@ -1230,8 +1241,7 @@ namespace ts { export type BinaryOperatorToken = Token; - // Binary expressions can be declarations if they are 'exports.foo = bar' expressions in JS files - export interface BinaryExpression extends Expression, Declaration { + export interface BinaryExpression extends Expression, Declaration { kind: SyntaxKind.BinaryExpression; left: Expression; operatorToken: BinaryOperatorToken; @@ -1431,7 +1441,7 @@ namespace ts { export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; export type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - export interface PropertyAccessExpression extends MemberExpression, Declaration { + export interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1521,7 +1531,7 @@ namespace ts { // for the same reasons we treat NewExpression as a PrimaryExpression. export interface MetaProperty extends PrimaryExpression { kind: SyntaxKind.MetaProperty; - keywordToken: SyntaxKind; + keywordToken: SyntaxKind.NewKeyword; name: Identifier; } @@ -1612,6 +1622,14 @@ namespace ts { kind: SyntaxKind.EndOfDeclarationMarker; } + /** + * A list of comma-seperated expressions. This node is only created by transformations. + */ + export interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; + elements: NodeArray; + } + /** * Marks the beginning of a merged transformed declaration. */ @@ -1777,7 +1795,7 @@ namespace ts { export type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - export interface ClassLikeDeclaration extends Declaration { + export interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1793,12 +1811,12 @@ namespace ts { kind: SyntaxKind.ClassExpression; } - export interface ClassElement extends Declaration { + export interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - export interface TypeElement extends Declaration { + export interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1826,7 +1844,7 @@ namespace ts { type: TypeNode; } - export interface EnumMember extends Declaration { + export interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; // This does include ComputedPropertyName, but the parser will give an error @@ -1915,14 +1933,14 @@ namespace ts { // import d, * as ns from "mod" => name = d, namedBinding: NamespaceImport = { name: ns } // import { a, b as x } from "mod" => name = undefined, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} // import d, { a, b as x } from "mod" => name = d, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} - export interface ImportClause extends Declaration { + export interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; // Default binding namedBindings?: NamedImportBindings; } - export interface NamespaceImport extends Declaration { + export interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1955,14 +1973,14 @@ namespace ts { export type NamedImportsOrExports = NamedImports | NamedExports; - export interface ImportSpecifier extends Declaration { + export interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) name: Identifier; // Declared name } - export interface ExportSpecifier extends Declaration { + export interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) @@ -2128,7 +2146,7 @@ namespace ts { typeExpression: JSDocTypeExpression; } - export interface JSDocTypedefTag extends JSDocTag, Declaration { + export interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -2424,6 +2442,8 @@ namespace ts { /* @internal */ isSourceFileFromExternalLibrary(file: SourceFile): boolean; // For testing purposes only. /* @internal */ structureIsReused?: StructureIsReused; + + /* @internal */ getSourceFileFromReference(referencingFile: SourceFile, ref: FileReference): SourceFile | undefined; } /* @internal */ @@ -2503,10 +2523,10 @@ namespace ts { getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; getDeclaredTypeOfSymbol(symbol: Symbol): Type; getPropertiesOfType(type: Type): Symbol[]; - getPropertyOfType(type: Type, propertyName: string): Symbol; - getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo; + getPropertyOfType(type: Type, propertyName: string): Symbol | undefined; + getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined; getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; - getIndexTypeOfType(type: Type, kind: IndexKind): Type; + getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined; getBaseTypes(type: InterfaceType): BaseType[]; getBaseTypeOfLiteralType(type: Type): Type; getWidenedType(type: Type): Type; @@ -2527,11 +2547,11 @@ namespace ts { indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; + getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; - getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; @@ -2541,16 +2561,16 @@ namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + getContextualType(node: Expression): Type | undefined; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; /* @internal */ getMergedSymbol(symbol: Symbol): Symbol; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; @@ -2560,15 +2580,18 @@ namespace ts { /** Unlike `getExportsOfModule`, this includes properties of an `export =` value. */ /* @internal */ getExportsAndPropertiesOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type; + getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; + getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; + getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; + /* @internal */ getBaseConstraintOfType(type: Type): Type | undefined; - /* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol; + /* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol | undefined; // Should not be called directly. Should only be accessed through the Program instance. /* @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -2579,22 +2602,43 @@ namespace ts { /* @internal */ getIdentifierCount(): number; /* @internal */ getSymbolCount(): number; /* @internal */ getTypeCount(): number; + + /** + * For a union, will include a property if it's defined in *any* of the member types. + * So for `{ a } | { b }`, this will include both `a` and `b`. + * Does not include properties of primitive types. + */ + /* @internal */ getAllPossiblePropertiesOfType(type: Type): Symbol[]; } export enum NodeBuilderFlags { None = 0, - allowThisInObjectLiteral = 1 << 0, - allowQualifedNameInPlaceOfIdentifier = 1 << 1, - allowTypeParameterInQualifiedName = 1 << 2, - allowAnonymousIdentifier = 1 << 3, - allowEmptyUnionOrIntersection = 1 << 4, - allowEmptyTuple = 1 << 5 + // Options + NoTruncation = 1 << 0, // Don't truncate result + WriteArrayAsGenericType = 1 << 1, // Write Array instead T[] + WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature + UseFullyQualifiedType = 1 << 6, // Write out the fully qualified type name (eg. Module.Type, instead of Type) + SuppressAnyReturnType = 1 << 8, // If the return type is any-like, don't offer a return type. + WriteTypeParametersInQualifiedName = 1 << 9, + + // Error handling + AllowThisInObjectLiteral = 1 << 10, + AllowQualifedNameInPlaceOfIdentifier = 1 << 11, + AllowAnonymousIdentifier = 1 << 13, + AllowEmptyUnionOrIntersection = 1 << 14, + AllowEmptyTuple = 1 << 15, + + IgnoreErrors = AllowThisInObjectLiteral | AllowQualifedNameInPlaceOfIdentifier | AllowAnonymousIdentifier | AllowEmptyUnionOrIntersection | AllowEmptyTuple, + + // State + InObjectTypeLiteral = 1 << 20, + InTypeAlias = 1 << 23, // Writing type in type alias declaration } export interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -2624,24 +2668,25 @@ namespace ts { // with import statements it previously saw (but chose not to emit). trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; reportInaccessibleThisError(): void; - reportIllegalExtends(): void; + reportPrivateInBaseOfClassExpression(propertyName: string): void; } export const enum TypeFormatFlags { - None = 0x00000000, - WriteArrayAsGenericType = 0x00000001, // Write Array instead T[] - UseTypeOfFunction = 0x00000002, // Write typeof instead of function type literal - NoTruncation = 0x00000004, // Don't truncate typeToString result - WriteArrowStyleSignature = 0x00000008, // Write arrow style signature - WriteOwnNameForAnyLike = 0x00000010, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc) - WriteTypeArgumentsOfSignature = 0x00000020, // Write the type arguments instead of type parameters of the signature - InElementType = 0x00000040, // Writing an array or union element type - UseFullyQualifiedType = 0x00000080, // Write out the fully qualified type name (eg. Module.Type, instead of Type) - InFirstTypeArgument = 0x00000100, // Writing first type argument of the instantiated type - InTypeAlias = 0x00000200, // Writing type in type alias declaration - UseTypeAliasValue = 0x00000400, // Serialize the type instead of using type-alias. This is needed when we emit declaration file. - SuppressAnyReturnType = 0x00000800, // If the return type is any-like, don't offer a return type. - AddUndefined = 0x00001000, // Add undefined to types of initialized, non-optional parameters + None = 0, + WriteArrayAsGenericType = 1 << 0, // Write Array instead T[] + UseTypeOfFunction = 1 << 2, // Write typeof instead of function type literal + NoTruncation = 1 << 3, // Don't truncate typeToString result + WriteArrowStyleSignature = 1 << 4, // Write arrow style signature + WriteOwnNameForAnyLike = 1 << 5, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc) + WriteTypeArgumentsOfSignature = 1 << 6, // Write the type arguments instead of type parameters of the signature + InElementType = 1 << 7, // Writing an array or union element type + UseFullyQualifiedType = 1 << 8, // Write out the fully qualified type name (eg. Module.Type, instead of Type) + InFirstTypeArgument = 1 << 9, // Writing first type argument of the instantiated type + InTypeAlias = 1 << 10, // Writing type in type alias declaration + UseTypeAliasValue = 1 << 11, // Serialize the type instead of using type-alias. This is needed when we emit declaration file. + SuppressAnyReturnType = 1 << 12, // If the return type is any-like, don't offer a return type. + AddUndefined = 1 << 13, // Add undefined to types of initialized, non-optional parameters + WriteClassExpressionAsTypeLiteral = 1 << 14, // Write a type literal instead of (Anonymous class) } export const enum SymbolFormatFlags { @@ -2744,16 +2789,15 @@ namespace ts { getNodeCheckFlags(node: Node): NodeCheckFlags; isDeclarationVisible(node: Declaration): boolean; collectLinkedAliases(node: Identifier): Node[]; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; isRequiredInitializedParameter(node: ParameterDeclaration): boolean; writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; - writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult; // Returns the constant value this property access resolves to, or 'undefined' for a non-constant - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number; getReferencedValueDeclaration(reference: Identifier): Declaration; getTypeReferenceSerializationKind(typeName: EntityName, location?: Node): TypeReferenceSerializationKind; isOptionalParameter(node: ParameterDeclaration): boolean; @@ -2891,6 +2935,13 @@ namespace ts { isDeclarationWithCollidingName?: boolean; // True if symbol is block scoped redeclaration bindingElement?: BindingElement; // Binding element associated with property symbol exportsSomeValue?: boolean; // True if module exports some value (not just types) + enumKind?: EnumKind; // Enum declaration classification + } + + /* @internal */ + export const enum EnumKind { + Numeric, // Numeric enum (each member has a TypeFlags.Enum type) + Literal // Literal enum (each member has a TypeFlags.EnumLiteral type) } /* @internal */ @@ -2963,7 +3014,7 @@ namespace ts { resolvedSymbol?: Symbol; // Cached name resolution result resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result maybeTypePredicate?: boolean; // Cached check whether call expression might reference a type predicate - enumMemberValue?: number; // Constant value of enum member + enumMemberValue?: string | number; // Constant value of enum member isVisible?: boolean; // Is this node visible containsArgumentsReference?: boolean; // Whether a function-like declaration contains an 'arguments' reference hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context @@ -2983,7 +3034,7 @@ namespace ts { StringLiteral = 1 << 5, NumberLiteral = 1 << 6, BooleanLiteral = 1 << 7, - EnumLiteral = 1 << 8, + EnumLiteral = 1 << 8, // Always combined with StringLiteral, NumberLiteral, or Union ESSymbol = 1 << 9, // Type of symbol primitive introduced in ES6 Void = 1 << 10, Undefined = 1 << 11, @@ -3009,7 +3060,7 @@ namespace ts { /* @internal */ Nullable = Undefined | Null, - Literal = StringLiteral | NumberLiteral | BooleanLiteral | EnumLiteral, + Literal = StringLiteral | NumberLiteral | BooleanLiteral, StringOrNumberLiteral = StringLiteral | NumberLiteral, /* @internal */ DefinitelyFalsy = StringLiteral | NumberLiteral | BooleanLiteral | Void | Undefined | Null, @@ -3017,9 +3068,9 @@ namespace ts { /* @internal */ Intrinsic = Any | String | Number | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never | NonPrimitive, /* @internal */ - Primitive = String | Number | Boolean | Enum | ESSymbol | Void | Undefined | Null | Literal, + Primitive = String | Number | Boolean | Enum | EnumLiteral | ESSymbol | Void | Undefined | Null | Literal, StringLike = String | StringLiteral | Index, - NumberLike = Number | NumberLiteral | Enum | EnumLiteral, + NumberLike = Number | NumberLiteral | Enum, BooleanLike = Boolean | BooleanLiteral, EnumLike = Enum | EnumLiteral, UnionOrIntersection = Union | Intersection, @@ -3058,19 +3109,21 @@ namespace ts { // String literal types (TypeFlags.StringLiteral) // Numeric literal types (TypeFlags.NumberLiteral) export interface LiteralType extends Type { - text: string; // Text of literal + value: string | number; // Value of literal freshType?: LiteralType; // Fresh version of type regularType?: LiteralType; // Regular version of type } - // Enum types (TypeFlags.Enum) - export interface EnumType extends Type { - memberTypes: EnumLiteralType[]; + export interface StringLiteralType extends LiteralType { + value: string; } - // Enum types (TypeFlags.EnumLiteral) - export interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; // Base enum type + export interface NumberLiteralType extends LiteralType { + value: number; + } + + // Enum types (TypeFlags.Enum) + export interface EnumType extends Type { } export const enum ObjectFlags { @@ -3127,7 +3180,7 @@ namespace ts { */ export interface TypeReference extends ObjectType { target: GenericType; // Type reference target - typeArguments: Type[]; // Type reference type arguments (undefined if none) + typeArguments?: Type[]; // Type reference type arguments (undefined if none) } // Generic class and interface types @@ -3257,7 +3310,7 @@ namespace ts { export interface Signature { declaration: SignatureDeclaration; // Originating declaration - typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic) + typeParameters?: TypeParameter[]; // Type parameters (undefined if non-generic) parameters: Symbol[]; // Parameters /* @internal */ thisParameter?: Symbol; // symbol of this-type parameter @@ -3368,9 +3421,9 @@ namespace ts { } export interface Diagnostic { - file: SourceFile; - start: number; - length: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; messageText: string | DiagnosticMessageChain; category: DiagnosticCategory; code: number; @@ -3380,7 +3433,7 @@ namespace ts { export enum DiagnosticCategory { Warning, Error, - Message, + Message } export enum ModuleResolutionKind { @@ -3520,7 +3573,7 @@ namespace ts { export const enum NewLineKind { CarriageReturnLineFeed = 0, - LineFeed = 1, + LineFeed = 1 } export interface LineAndCharacter { @@ -3944,7 +3997,7 @@ namespace ts { commentRange?: TextRange; // The text range to use when emitting leading or trailing comments sourceMapRange?: TextRange; // The text range to use when emitting leading or trailing source mappings tokenSourceMapRanges?: TextRange[]; // The text range to use when emitting source mappings for tokens - constantValue?: number; // The constant value of an expression + constantValue?: string | number; // The constant value of an expression externalHelpersModuleName?: Identifier; // The local name for an imported helpers module helpers?: EmitHelper[]; // Emit helpers for the node } @@ -3977,6 +4030,7 @@ namespace ts { NoHoisting = 1 << 21, // Do not hoist this declaration in --module system HasEndOfDeclarationMarker = 1 << 22, // Declaration has an associated NotEmittedStatement to mark the end of the declaration Iterator = 1 << 23, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable. + NoAsciiEscaping = 1 << 24, // When synthesizing nodes that lack an original node or textSourceNode, we want to write the text on the node with ASCII escaping substitutions. } export interface EmitHelper { @@ -4001,11 +4055,12 @@ namespace ts { Awaiter = 1 << 6, // __awaiter (used by ES2017 async functions transformation) Generator = 1 << 7, // __generator (used by ES2015 generator transformation) Values = 1 << 8, // __values (used by ES2015 for..of and yield* transformations) - Read = 1 << 9, // __read (used by ES2015 iterator destructuring transformation) + Read = 1 << 9, // __read (used by ES2015 iterator destructuring transformation) Spread = 1 << 10, // __spread (used by ES2015 array spread and argument list spread transformations) - AsyncGenerator = 1 << 11, // __asyncGenerator (used by ES2017 async generator transformation) - AsyncDelegator = 1 << 12, // __asyncDelegator (used by ES2017 async generator yield* transformation) - AsyncValues = 1 << 13, // __asyncValues (used by ES2017 for..await..of transformation) + Await = 1 << 11, // __await (used by ES2017 async generator transformation) + AsyncGenerator = 1 << 12, // __asyncGenerator (used by ES2017 async generator transformation) + AsyncDelegator = 1 << 13, // __asyncDelegator (used by ES2017 async generator yield* transformation) + AsyncValues = 1 << 14, // __asyncValues (used by ES2017 for..await..of transformation) // Helpers included by ES2015 for..of ForOfIncludes = Values, @@ -4013,6 +4068,12 @@ namespace ts { // Helpers included by ES2017 for..await..of ForAwaitOfIncludes = AsyncValues, + // Helpers included by ES2017 async generators + AsyncGeneratorIncludes = Await | AsyncGenerator, + + // Helpers included by yield* in ES2017 async generators + AsyncDelegatorIncludes = Await | AsyncDelegator | AsyncValues, + // Helpers included by ES2015 spread SpreadIncludes = Read | Spread, @@ -4182,7 +4243,7 @@ namespace ts { * Prints a bundle of source files as-is, without any emit transformations. */ printBundle(bundle: Bundle): string; - /*@internal*/ writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile, writer: EmitTextWriter): void; + /*@internal*/ writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void; /*@internal*/ writeFile(sourceFile: SourceFile, writer: EmitTextWriter): void; /*@internal*/ writeBundle(bundle: Bundle, writer: EmitTextWriter): void; } @@ -4236,6 +4297,8 @@ namespace ts { /*@internal*/ onSetSourceFile?: (node: SourceFile) => void; /*@internal*/ onBeforeEmitNodeArray?: (nodes: NodeArray) => void; /*@internal*/ onAfterEmitNodeArray?: (nodes: NodeArray) => void; + /*@internal*/ onBeforeEmitToken?: (node: Node) => void; + /*@internal*/ onAfterEmitToken?: (node: Node) => void; } export interface PrinterOptions { diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 66eb5119bbd..ef9e295349a 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -11,12 +11,12 @@ namespace ts { isTypeReferenceDirective?: boolean; } - export function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration { + export function getDeclarationOfKind(symbol: Symbol, kind: T["kind"]): T { const declarations = symbol.declarations; if (declarations) { for (const declaration of declarations) { if (declaration.kind === kind) { - return declaration; + return declaration as T; } } } @@ -68,7 +68,7 @@ namespace ts { clear: () => str = "", trackSymbol: noop, reportInaccessibleThisError: noop, - reportIllegalExtends: noop + reportPrivateInBaseOfClassExpression: noop, }; } @@ -328,19 +328,21 @@ namespace ts { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + const escapeText = getEmitFlags(node) & EmitFlags.NoAsciiEscaping ? escapeString : escapeNonAsciiString; + // If we can't reach the original source text, use the canonical form if it's a number, - // or an escaped quoted form of the original text if it's string-like. + // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { case SyntaxKind.StringLiteral: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case SyntaxKind.NoSubstitutionTemplateLiteral: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case SyntaxKind.TemplateHead: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case SyntaxKind.TemplateMiddle: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case SyntaxKind.TemplateTail: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case SyntaxKind.NumericLiteral: return node.text; } @@ -348,8 +350,8 @@ namespace ts { Debug.fail(`Literal kind '${node.kind}' not accounted for.`); } - function getQuotedEscapedLiteralText(leftQuote: string, text: string, rightQuote: string) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + export function getTextOfConstantValue(value: string | number) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' @@ -465,7 +467,7 @@ namespace ts { return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } - export function getNameFromIndexInfo(info: IndexInfo) { + export function getNameFromIndexInfo(info: IndexInfo): string | undefined { return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; } @@ -566,7 +568,7 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.TypeAliasDeclaration: - errorNode = (node).name; + errorNode = (node).name; break; case SyntaxKind.ArrowFunction: return getErrorSpanForArrowFunction(sourceFile, node); @@ -589,10 +591,6 @@ namespace ts { return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } - export function isDeclarationFile(file: SourceFile): boolean { - return file.isDeclarationFile; - } - export function isConstEnumDeclaration(node: Node): boolean { return node.kind === SyntaxKind.EnumDeclaration && isConst(node); } @@ -885,6 +883,16 @@ namespace ts { return false; } + export function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode { + switch (node.kind) { + case SyntaxKind.FunctionType: + case SyntaxKind.ConstructorType: + return true; + } + + return false; + } + export function introducesArgumentsExoticObject(node: Node) { switch (node.kind) { case SyntaxKind.MethodDeclaration: @@ -1146,6 +1154,10 @@ namespace ts { } } + export function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression { + return node.kind === SyntaxKind.CallExpression || node.kind === SyntaxKind.NewExpression; + } + export function getInvokedExpression(node: CallLikeExpression): Expression { if (node.kind === SyntaxKind.TaggedTemplateExpression) { return (node).tag; @@ -1591,7 +1603,7 @@ namespace ts { // Pull parameter comments from declaring function as well if (node.kind === SyntaxKind.Parameter) { - cache = concatenate(cache, getJSDocParameterTags(node)); + cache = concatenate(cache, getJSDocParameterTags(node as ParameterDeclaration)); } if (isVariableLike(node) && node.initializer) { @@ -1602,11 +1614,8 @@ namespace ts { } } - export function getJSDocParameterTags(param: Node): JSDocParameterTag[] { - if (!isParameter(param)) { - return undefined; - } - const func = param.parent as FunctionLikeDeclaration; + export function getJSDocParameterTags(param: ParameterDeclaration): JSDocParameterTag[] { + const func = param.parent; const tags = getJSDocTags(func, SyntaxKind.JSDocParameterTag) as JSDocParameterTag[]; if (!param.name) { // this is an anonymous jsdoc param from a `function(type1, type2): type3` specification @@ -1627,10 +1636,22 @@ namespace ts { } } + /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ + export function getParameterFromJSDoc(node: JSDocParameterTag): ParameterDeclaration | undefined { + const name = node.parameterName.text; + const grandParent = node.parent!.parent!; + Debug.assert(node.parent!.kind === SyntaxKind.JSDocComment); + if (!isFunctionLike(grandParent)) { + return undefined; + } + return find(grandParent.parameters, p => + p.name.kind === SyntaxKind.Identifier && p.name.text === name); + } + export function getJSDocType(node: Node): JSDocType { let tag: JSDocTypeTag | JSDocParameterTag = getFirstJSDocTag(node, SyntaxKind.JSDocTypeTag) as JSDocTypeTag; if (!tag && node.kind === SyntaxKind.Parameter) { - const paramTags = getJSDocParameterTags(node); + const paramTags = getJSDocParameterTags(node as ParameterDeclaration); if (paramTags) { tag = find(paramTags, tag => !!tag.typeExpression); } @@ -1758,22 +1779,31 @@ namespace ts { // True if the given identifier, string literal, or number literal is the name of a declaration node export function isDeclarationName(name: Node): boolean { - if (name.kind !== SyntaxKind.Identifier && name.kind !== SyntaxKind.StringLiteral && name.kind !== SyntaxKind.NumericLiteral) { - return false; + switch (name.kind) { + case SyntaxKind.Identifier: + case SyntaxKind.StringLiteral: + case SyntaxKind.NumericLiteral: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } + } - const parent = name.parent; - if (parent.kind === SyntaxKind.ImportSpecifier || parent.kind === SyntaxKind.ExportSpecifier) { - if ((parent).propertyName) { - return true; - } + /* @internal */ + // See GH#16030 + export function isAnyDeclarationName(name: Node): boolean { + switch (name.kind) { + case SyntaxKind.Identifier: + case SyntaxKind.StringLiteral: + case SyntaxKind.NumericLiteral: + if (isDeclaration(name.parent)) { + return name.parent.name === name; + } + const binExp = name.parent.parent; + return isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== SpecialPropertyAssignmentKind.None && getNameOfDeclaration(binExp) === name; + default: + return false; } - - if (isDeclaration(parent)) { - return (parent).name === name; - } - - return false; } export function isLiteralComputedPropertyDeclarationName(node: Node) { @@ -1796,7 +1826,7 @@ namespace ts { case SyntaxKind.PropertyAssignment: case SyntaxKind.PropertyAccessExpression: // Name in member declaration or property name in property access - return (parent).name === node; + return (parent).name === node; case SyntaxKind.QualifiedName: // Name on right hand side of dot in a type query if ((parent).right === node) { @@ -1888,21 +1918,19 @@ namespace ts { const isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { const refMatchResult = fullTripleSlashReferencePathRegEx.exec(comment); const refLibResult = !refMatchResult && fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - const start = commentRange.pos; - const end = commentRange.end; + const match = refMatchResult || refLibResult; + if (match) { + const pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -1928,16 +1956,18 @@ namespace ts { } export const enum FunctionFlags { - Normal = 0, - Generator = 1 << 0, - Async = 1 << 1, - AsyncOrAsyncGenerator = Async | Generator, - Invalid = 1 << 2, - InvalidAsyncOrAsyncGenerator = AsyncOrAsyncGenerator | Invalid, - InvalidGenerator = Generator | Invalid, + Normal = 0, // Function is a normal function + Generator = 1 << 0, // Function is a generator function or async generator function + Async = 1 << 1, // Function is an async function or an async generator function + Invalid = 1 << 2, // Function is a signature or overload and does not have a body. + AsyncGenerator = Async | Generator, // Function is an async generator function } - export function getFunctionFlags(node: FunctionLikeDeclaration) { + export function getFunctionFlags(node: FunctionLikeDeclaration | undefined) { + if (!node) { + return FunctionFlags.Invalid; + } + let flags = FunctionFlags.Normal; switch (node.kind) { case SyntaxKind.FunctionDeclaration: @@ -1992,7 +2022,8 @@ namespace ts { * Symbol. */ export function hasDynamicName(declaration: Declaration): boolean { - return declaration.name && isDynamicName(declaration.name); + const name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } export function isDynamicName(name: DeclarationName): boolean { @@ -2302,6 +2333,9 @@ namespace ts { case SyntaxKind.SpreadElement: return 1; + case SyntaxKind.CommaListExpression: + return 0; + default: return -1; } @@ -2434,7 +2468,8 @@ namespace ts { } const nonAsciiCharacters = /[^\u0000-\u007F]/g; - export function escapeNonAsciiCharacters(s: string): string { + export function escapeNonAsciiString(s: string): string { + s = escapeString(s); // Replace non-ASCII characters with '\uNNNN' escapes if any exist. // Otherwise just return the original string. return nonAsciiCharacters.test(s) ? @@ -2538,7 +2573,7 @@ namespace ts { export function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): string { const file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -2611,7 +2646,7 @@ namespace ts { /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ export function sourceFileMayBeEmitted(sourceFile: SourceFile, options: CompilerOptions, isSourceFileFromExternalLibrary: (file: SourceFile) => boolean) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } /** @@ -2757,7 +2792,7 @@ namespace ts { forEach(declarations, (member: Declaration) => { if ((member.kind === SyntaxKind.GetAccessor || member.kind === SyntaxKind.SetAccessor) && hasModifier(member, ModifierFlags.Static) === hasModifier(accessor, ModifierFlags.Static)) { - const memberName = getPropertyNameForPropertyNameNode(member.name); + const memberName = getPropertyNameForPropertyNameNode((member as NamedDeclaration).name); const accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { if (!firstAccessor) { @@ -3137,11 +3172,11 @@ namespace ts { } export function getLocalSymbolForExportDefault(symbol: Symbol) { - return isExportDefaultSymbol(symbol) ? symbol.valueDeclaration.localSymbol : undefined; + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; } function isExportDefaultSymbol(symbol: Symbol): boolean { - return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, ModifierFlags.Default); + return symbol && length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], ModifierFlags.Default); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ @@ -3227,13 +3262,13 @@ namespace ts { const carriageReturnLineFeed = "\r\n"; const lineFeed = "\n"; export function getNewLineCharacter(options: CompilerOptions | PrinterOptions): string { - if (options.newLine === NewLineKind.CarriageReturnLineFeed) { - return carriageReturnLineFeed; + switch (options.newLine) { + case NewLineKind.CarriageReturnLineFeed: + return carriageReturnLineFeed; + case NewLineKind.LineFeed: + return lineFeed; } - else if (options.newLine === NewLineKind.LineFeed) { - return lineFeed; - } - else if (sys) { + if (sys) { return sys.newLine; } return carriageReturnLineFeed; @@ -3572,10 +3607,6 @@ namespace ts { return node.kind === SyntaxKind.Identifier; } - export function isVoidExpression(node: Node): node is VoidExpression { - return node.kind === SyntaxKind.VoidExpression; - } - export function isGeneratedIdentifier(node: Node): node is GeneratedIdentifier { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return isIdentifier(node) && node.autoGenerateKind > GeneratedIdentifierKind.None; @@ -3652,7 +3683,18 @@ namespace ts { || kind === SyntaxKind.GetAccessor || kind === SyntaxKind.SetAccessor || kind === SyntaxKind.IndexSignature - || kind === SyntaxKind.SemicolonClassElement; + || kind === SyntaxKind.SemicolonClassElement + || kind === SyntaxKind.MissingDeclaration; + } + + export function isTypeElement(node: Node): node is TypeElement { + const kind = node.kind; + return kind === SyntaxKind.ConstructSignature + || kind === SyntaxKind.CallSignature + || kind === SyntaxKind.PropertySignature + || kind === SyntaxKind.MethodSignature + || kind === SyntaxKind.IndexSignature + || kind === SyntaxKind.MissingDeclaration; } export function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike { @@ -3883,6 +3925,7 @@ namespace ts { || kind === SyntaxKind.SpreadElement || kind === SyntaxKind.AsExpression || kind === SyntaxKind.OmittedExpression + || kind === SyntaxKind.CommaListExpression || isUnaryExpressionKind(kind); } @@ -3974,6 +4017,10 @@ namespace ts { return node.kind === SyntaxKind.ImportEqualsDeclaration; } + export function isImportDeclaration(node: Node): node is ImportDeclaration { + return node.kind === SyntaxKind.ImportDeclaration; + } + export function isImportClause(node: Node): node is ImportClause { return node.kind === SyntaxKind.ImportClause; } @@ -3996,6 +4043,10 @@ namespace ts { return node.kind === SyntaxKind.ExportSpecifier; } + export function isExportAssignment(node: Node): node is ExportAssignment { + return node.kind === SyntaxKind.ExportAssignment; + } + export function isModuleOrEnumDeclaration(node: Node): node is ModuleDeclaration | EnumDeclaration { return node.kind === SyntaxKind.ModuleDeclaration || node.kind === SyntaxKind.EnumDeclaration; } @@ -4073,7 +4124,7 @@ namespace ts { || kind === SyntaxKind.MergeDeclarationMarker; } - export function isDeclaration(node: Node): node is Declaration { + export function isDeclaration(node: Node): node is NamedDeclaration { return isDeclarationKind(node.kind); } @@ -4202,6 +4253,52 @@ namespace ts { // Firefox has Object.prototype.watch return options.watch && options.hasOwnProperty("watch"); } + + export function getCheckFlags(symbol: Symbol): CheckFlags { + return symbol.flags & SymbolFlags.Transient ? (symbol).checkFlags : 0; + } + + export function getDeclarationModifierFlagsFromSymbol(s: Symbol): ModifierFlags { + if (s.valueDeclaration) { + const flags = getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & SymbolFlags.Class ? flags : flags & ~ModifierFlags.AccessibilityModifier; + } + if (getCheckFlags(s) & CheckFlags.Synthetic) { + const checkFlags = (s).checkFlags; + const accessModifier = checkFlags & CheckFlags.ContainsPrivate ? ModifierFlags.Private : + checkFlags & CheckFlags.ContainsPublic ? ModifierFlags.Public : + ModifierFlags.Protected; + const staticModifier = checkFlags & CheckFlags.ContainsStatic ? ModifierFlags.Static : 0; + return accessModifier | staticModifier; + } + if (s.flags & SymbolFlags.Prototype) { + return ModifierFlags.Public | ModifierFlags.Static; + } + return 0; + } + + export function levenshtein(s1: string, s2: string): number { + let previous: number[] = new Array(s2.length + 1); + let current: number[] = new Array(s2.length + 1); + for (let i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (let i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (let j = 1; j < s2.length + 1; j++) { + current[j] = Math.min( + previous[j] + 1, + current[j - 1] + 1, + previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + // shift current back to previous, and then reuse previous' array + const tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } } namespace ts { @@ -4632,4 +4729,25 @@ namespace ts { export function unescapeIdentifier(identifier: string): string { return identifier.length >= 3 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ && identifier.charCodeAt(2) === CharacterCodes._ ? identifier.substr(1) : identifier; } + + export function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined { + if (!declaration) { + return undefined; + } + if (declaration.kind === SyntaxKind.BinaryExpression) { + const expr = declaration as BinaryExpression; + switch (getSpecialPropertyAssignmentKind(expr)) { + case SpecialPropertyAssignmentKind.ExportsProperty: + case SpecialPropertyAssignmentKind.ThisProperty: + case SpecialPropertyAssignmentKind.Property: + case SpecialPropertyAssignmentKind.PrototypeProperty: + return (expr.left as PropertyAccessExpression).name; + default: + return undefined; + } + } + else { + return (declaration as NamedDeclaration).name; + } + } } diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 54cea3168e1..fa642b7a3c4 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -218,17 +218,12 @@ namespace ts { return node; } - switch (node.kind) { - case SyntaxKind.SemicolonClassElement: - case SyntaxKind.EmptyStatement: - case SyntaxKind.OmittedExpression: - case SyntaxKind.DebuggerStatement: - case SyntaxKind.EndOfDeclarationMarker: - case SyntaxKind.MissingDeclaration: - // No need to visit nodes with no children. - return node; - + switch (kind) { // Names + + case SyntaxKind.Identifier: + return updateIdentifier(node, nodesVisitor((node).typeArguments, visitor, isTypeNode)); + case SyntaxKind.QualifiedName: return updateQualifiedName(node, visitNode((node).left, visitor, isEntityName), @@ -238,45 +233,13 @@ namespace ts { return updateComputedPropertyName(node, visitNode((node).expression, visitor, isExpression)); - // Signatures and Signature Elements - case SyntaxKind.FunctionType: - return updateFunctionTypeNode(node, - nodesVisitor((node).typeParameters, visitor, isTypeParameter), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - visitNode((node).type, visitor, isTypeNode)); + // Signature elements - case SyntaxKind.ConstructorType: - return updateConstructorTypeNode(node, - nodesVisitor((node).typeParameters, visitor, isTypeParameter), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.CallSignature: - return updateCallSignatureDeclaration(node, - nodesVisitor((node).typeParameters, visitor, isTypeParameter), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.ConstructSignature: - return updateConstructSignatureDeclaration(node, - nodesVisitor((node).typeParameters, visitor, isTypeParameter), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.MethodSignature: - return updateMethodSignature(node, - nodesVisitor((node).typeParameters, visitor, isTypeParameter), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - visitNode((node).type, visitor, isTypeNode), - visitNode((node).name, visitor, isPropertyName), - visitNode((node).questionToken, tokenVisitor, isToken)); - - case SyntaxKind.IndexSignature: - return updateIndexSignatureDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - visitNode((node).type, visitor, isTypeNode)); + case SyntaxKind.TypeParameter: + return updateTypeParameterDeclaration(node, + visitNode((node).name, visitor, isIdentifier), + visitNode((node).constraint, visitor, isTypeNode), + visitNode((node).default, visitor, isTypeNode)); case SyntaxKind.Parameter: return updateParameter(node, @@ -292,70 +255,11 @@ namespace ts { return updateDecorator(node, visitNode((node).expression, visitor, isExpression)); - // Types - - case SyntaxKind.TypeReference: - return updateTypeReferenceNode(node, - visitNode((node).typeName, visitor, isEntityName), - nodesVisitor((node).typeArguments, visitor, isTypeNode)); - - case SyntaxKind.TypePredicate: - return updateTypePredicateNode(node, - visitNode((node).parameterName, visitor), - visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.TypeQuery: - return updateTypeQueryNode((node), visitNode((node).exprName, visitor, isEntityName)); - - case SyntaxKind.TypeLiteral: - return updateTypeLiteralNode((node), nodesVisitor((node).members, visitor)); - - case SyntaxKind.ArrayType: - return updateArrayTypeNode(node, visitNode((node).elementType, visitor, isTypeNode)); - - case SyntaxKind.TupleType: - return updateTypleTypeNode((node), nodesVisitor((node).elementTypes, visitor, isTypeNode)); - - case SyntaxKind.UnionType: - case SyntaxKind.IntersectionType: - return updateUnionOrIntersectionTypeNode(node, - nodesVisitor((node).types, visitor, isTypeNode)); - - case SyntaxKind.ParenthesizedType: - return updateParenthesizedType(node, - visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.TypeOperator: - return updateTypeOperatorNode(node, visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.IndexedAccessType: - return updateIndexedAccessTypeNode((node), - visitNode((node).objectType, visitor, isTypeNode), - visitNode((node).indexType, visitor, isTypeNode)); - - case SyntaxKind.MappedType: - return updateMappedTypeNode((node), - visitNode((node).readonlyToken, tokenVisitor, isToken), - visitNode((node).typeParameter, visitor, isTypeParameter), - visitNode((node).questionToken, tokenVisitor, isToken), - visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.LiteralType: - return updateLiteralTypeNode(node, - visitNode((node).literal, visitor, isExpression)); - - // Type Declarations - - case SyntaxKind.TypeParameter: - return updateTypeParameterDeclaration(node, - visitNode((node).name, visitor, isIdentifier), - visitNode((node).constraint, visitor, isTypeNode), - visitNode((node).default, visitor, isTypeNode)); - - // Type members + // Type elements case SyntaxKind.PropertySignature: return updatePropertySignature((node), + nodesVisitor((node).modifiers, visitor, isToken), visitNode((node).name, visitor, isPropertyName), visitNode((node).questionToken, tokenVisitor, isToken), visitNode((node).type, visitor, isTypeNode), @@ -369,6 +273,14 @@ namespace ts { visitNode((node).type, visitor, isTypeNode), visitNode((node).initializer, visitor, isExpression)); + case SyntaxKind.MethodSignature: + return updateMethodSignature(node, + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + nodesVisitor((node).parameters, visitor, isParameterDeclaration), + visitNode((node).type, visitor, isTypeNode), + visitNode((node).name, visitor, isPropertyName), + visitNode((node).questionToken, tokenVisitor, isToken)); + case SyntaxKind.MethodDeclaration: return updateMethod(node, nodesVisitor((node).decorators, visitor, isDecorator), @@ -405,7 +317,99 @@ namespace ts { visitParameterList((node).parameters, visitor, context, nodesVisitor), visitFunctionBody((node).body, visitor, context)); + case SyntaxKind.CallSignature: + return updateCallSignature(node, + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + nodesVisitor((node).parameters, visitor, isParameterDeclaration), + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.ConstructSignature: + return updateConstructSignature(node, + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + nodesVisitor((node).parameters, visitor, isParameterDeclaration), + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.IndexSignature: + return updateIndexSignature(node, + nodesVisitor((node).decorators, visitor, isDecorator), + nodesVisitor((node).modifiers, visitor, isModifier), + nodesVisitor((node).parameters, visitor, isParameterDeclaration), + visitNode((node).type, visitor, isTypeNode)); + + // Types + + case SyntaxKind.TypePredicate: + return updateTypePredicateNode(node, + visitNode((node).parameterName, visitor), + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.TypeReference: + return updateTypeReferenceNode(node, + visitNode((node).typeName, visitor, isEntityName), + nodesVisitor((node).typeArguments, visitor, isTypeNode)); + + case SyntaxKind.FunctionType: + return updateFunctionTypeNode(node, + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + nodesVisitor((node).parameters, visitor, isParameterDeclaration), + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.ConstructorType: + return updateConstructorTypeNode(node, + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + nodesVisitor((node).parameters, visitor, isParameterDeclaration), + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.TypeQuery: + return updateTypeQueryNode((node), + visitNode((node).exprName, visitor, isEntityName)); + + case SyntaxKind.TypeLiteral: + return updateTypeLiteralNode((node), + nodesVisitor((node).members, visitor, isTypeElement)); + + case SyntaxKind.ArrayType: + return updateArrayTypeNode(node, + visitNode((node).elementType, visitor, isTypeNode)); + + case SyntaxKind.TupleType: + return updateTypleTypeNode((node), + nodesVisitor((node).elementTypes, visitor, isTypeNode)); + + case SyntaxKind.UnionType: + return updateUnionTypeNode(node, + nodesVisitor((node).types, visitor, isTypeNode)); + + case SyntaxKind.IntersectionType: + return updateIntersectionTypeNode(node, + nodesVisitor((node).types, visitor, isTypeNode)); + + case SyntaxKind.ParenthesizedType: + return updateParenthesizedType(node, + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.TypeOperator: + return updateTypeOperatorNode(node, + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.IndexedAccessType: + return updateIndexedAccessTypeNode((node), + visitNode((node).objectType, visitor, isTypeNode), + visitNode((node).indexType, visitor, isTypeNode)); + + case SyntaxKind.MappedType: + return updateMappedTypeNode((node), + visitNode((node).readonlyToken, tokenVisitor, isToken), + visitNode((node).typeParameter, visitor, isTypeParameter), + visitNode((node).questionToken, tokenVisitor, isToken), + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.LiteralType: + return updateLiteralTypeNode(node, + visitNode((node).literal, visitor, isExpression)); + // Binding patterns + case SyntaxKind.ObjectBindingPattern: return updateObjectBindingPattern(node, nodesVisitor((node).elements, visitor, isBindingElement)); @@ -422,6 +426,7 @@ namespace ts { visitNode((node).initializer, visitor, isExpression)); // Expression + case SyntaxKind.ArrayLiteralExpression: return updateArrayLiteral(node, nodesVisitor((node).elements, visitor, isExpression)); @@ -500,11 +505,6 @@ namespace ts { return updateAwait(node, visitNode((node).expression, visitor, isExpression)); - case SyntaxKind.BinaryExpression: - return updateBinary(node, - visitNode((node).left, visitor, isExpression), - visitNode((node).right, visitor, isExpression)); - case SyntaxKind.PrefixUnaryExpression: return updatePrefix(node, visitNode((node).operand, visitor, isExpression)); @@ -513,6 +513,12 @@ namespace ts { return updatePostfix(node, visitNode((node).operand, visitor, isExpression)); + case SyntaxKind.BinaryExpression: + return updateBinary(node, + visitNode((node).left, visitor, isExpression), + visitNode((node).right, visitor, isExpression), + visitNode((node).operatorToken, visitor, isToken)); + case SyntaxKind.ConditionalExpression: return updateConditional(node, visitNode((node).condition, visitor, isExpression), @@ -555,13 +561,19 @@ namespace ts { return updateNonNullExpression(node, visitNode((node).expression, visitor, isExpression)); + case SyntaxKind.MetaProperty: + return updateMetaProperty(node, + visitNode((node).name, visitor, isIdentifier)); + // Misc + case SyntaxKind.TemplateSpan: return updateTemplateSpan(node, visitNode((node).expression, visitor, isExpression), visitNode((node).literal, visitor, isTemplateMiddleOrTemplateTail)); // Element + case SyntaxKind.Block: return updateBlock(node, nodesVisitor((node).statements, visitor, isStatement)); @@ -678,6 +690,23 @@ namespace ts { nodesVisitor((node).heritageClauses, visitor, isHeritageClause), nodesVisitor((node).members, visitor, isClassElement)); + case SyntaxKind.InterfaceDeclaration: + return updateInterfaceDeclaration(node, + nodesVisitor((node).decorators, visitor, isDecorator), + nodesVisitor((node).modifiers, visitor, isModifier), + visitNode((node).name, visitor, isIdentifier), + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + nodesVisitor((node).heritageClauses, visitor, isHeritageClause), + nodesVisitor((node).members, visitor, isTypeElement)); + + case SyntaxKind.TypeAliasDeclaration: + return updateTypeAliasDeclaration(node, + nodesVisitor((node).decorators, visitor, isDecorator), + nodesVisitor((node).modifiers, visitor, isModifier), + visitNode((node).name, visitor, isIdentifier), + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + visitNode((node).type, visitor, isTypeNode)); + case SyntaxKind.EnumDeclaration: return updateEnumDeclaration(node, nodesVisitor((node).decorators, visitor, isDecorator), @@ -700,6 +729,10 @@ namespace ts { return updateCaseBlock(node, nodesVisitor((node).clauses, visitor, isCaseOrDefaultClause)); + case SyntaxKind.NamespaceExportDeclaration: + return updateNamespaceExportDeclaration(node, + visitNode((node).name, visitor, isIdentifier)); + case SyntaxKind.ImportEqualsDeclaration: return updateImportEqualsDeclaration(node, nodesVisitor((node).decorators, visitor, isDecorator), @@ -755,21 +788,19 @@ namespace ts { visitNode((node).name, visitor, isIdentifier)); // Module references + case SyntaxKind.ExternalModuleReference: return updateExternalModuleReference(node, visitNode((node).expression, visitor, isExpression)); // JSX + case SyntaxKind.JsxElement: return updateJsxElement(node, visitNode((node).openingElement, visitor, isJsxOpeningElement), nodesVisitor((node).children, visitor, isJsxChild), visitNode((node).closingElement, visitor, isJsxClosingElement)); - case SyntaxKind.JsxAttributes: - return updateJsxAttributes(node, - nodesVisitor((node).properties, visitor, isJsxAttributeLike)); - case SyntaxKind.JsxSelfClosingElement: return updateJsxSelfClosingElement(node, visitNode((node).tagName, visitor, isJsxTagNameExpression), @@ -789,6 +820,10 @@ namespace ts { visitNode((node).name, visitor, isIdentifier), visitNode((node).initializer, visitor, isStringLiteralOrJsxExpression)); + case SyntaxKind.JsxAttributes: + return updateJsxAttributes(node, + nodesVisitor((node).properties, visitor, isJsxAttributeLike)); + case SyntaxKind.JsxSpreadAttribute: return updateJsxSpreadAttribute(node, visitNode((node).expression, visitor, isExpression)); @@ -798,6 +833,7 @@ namespace ts { visitNode((node).expression, visitor, isExpression)); // Clauses + case SyntaxKind.CaseClause: return updateCaseClause(node, visitNode((node).expression, visitor, isExpression), @@ -817,6 +853,7 @@ namespace ts { visitNode((node).block, visitor, isBlock)); // Property assignments + case SyntaxKind.PropertyAssignment: return updatePropertyAssignment(node, visitNode((node).name, visitor, isPropertyName), @@ -847,9 +884,15 @@ namespace ts { return updatePartiallyEmittedExpression(node, visitNode((node).expression, visitor, isExpression)); + case SyntaxKind.CommaListExpression: + return updateCommaList(node, + nodesVisitor((node).elements, visitor, isExpression)); + default: + // No need to visit nodes with no children. return node; } + } /** @@ -935,6 +978,15 @@ namespace ts { break; // Type member + + case SyntaxKind.PropertySignature: + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNode((node).questionToken, cbNode, result); + result = reduceNode((node).type, cbNode, result); + result = reduceNode((node).initializer, cbNode, result); + break; + case SyntaxKind.PropertyDeclaration: result = reduceNodes((node).decorators, cbNodes, result); result = reduceNodes((node).modifiers, cbNodes, result); @@ -1358,6 +1410,10 @@ namespace ts { result = reduceNode((node).expression, cbNode, result); break; + case SyntaxKind.CommaListExpression: + result = reduceNodes((node).elements, cbNodes, result); + break; + default: break; } diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index a56d21ae345..8f19b83c7ad 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -655,7 +655,7 @@ namespace FourSlash { ts.zipWith(endMarkers, definitions, (endMarker, definition, i) => { const marker = this.getMarkerByName(endMarker); if (marker.fileName !== definition.fileName || marker.position !== definition.textSpan.start) { - this.raiseError(`goToDefinition failed for definition ${i}: expected ${marker.fileName} at ${marker.position}, got ${definition.fileName} at ${definition.textSpan.start}`); + this.raiseError(`goToDefinition failed for definition ${endMarker} (${i}): expected ${marker.fileName} at ${marker.position}, got ${definition.fileName} at ${definition.textSpan.start}`); } }); } @@ -916,7 +916,7 @@ namespace FourSlash { } private getNode(): ts.Node { - return ts.getTouchingPropertyName(this.getSourceFile(), this.currentCaretPosition); + return ts.getTouchingPropertyName(this.getSourceFile(), this.currentCaretPosition, /*includeJsDocComment*/ false); } private goToAndGetNode(range: Range): ts.Node { @@ -994,17 +994,15 @@ namespace FourSlash { } public verifyReferenceGroups(startRanges: Range | Range[], parts: Array<{ definition: string, ranges: Range[] }>): void { - interface ReferenceJson { definition: string; ranges: ts.ReferenceEntry[]; } - type ReferencesJson = ReferenceJson[]; - const fullExpected = parts.map(({ definition, ranges }) => ({ definition, ranges: ranges.map(rangeToReferenceEntry) })); + const fullExpected = ts.map(parts, ({ definition, ranges }) => ({ definition, ranges: ranges.map(rangeToReferenceEntry) })); for (const startRange of toArray(startRanges)) { this.goToRangeStart(startRange); - const fullActual = ts.map(this.findReferencesAtCaret(), ({ definition, references }) => ({ + const fullActual = ts.map(this.findReferencesAtCaret(), ({ definition, references }) => ({ definition: definition.displayParts.map(d => d.text).join(""), ranges: references })); - this.assertObjectsEqual(fullActual, fullExpected); + this.assertObjectsEqual(fullActual, fullExpected); } function rangeToReferenceEntry(r: Range): ts.ReferenceEntry { @@ -1047,6 +1045,10 @@ namespace FourSlash { this.raiseError(`${msgPrefix}At ${path}: ${msg}`); }; + if ((actual === undefined) !== (expected === undefined)) { + fail(`Expected ${expected}, got ${actual}`); + } + for (const key in actual) if (ts.hasProperty(actual as any, key)) { const ak = actual[key], ek = expected[key]; if (typeof ak === "object" && typeof ek === "object") { @@ -1062,6 +1064,14 @@ namespace FourSlash { } } }; + if (fullActual === undefined || fullExpected === undefined) { + if (fullActual === fullExpected) { + return; + } + console.log("Expected:", stringify(fullExpected)); + console.log("Actual: ", stringify(fullActual)); + this.raiseError(msgPrefix); + } recur(fullActual, fullExpected, ""); } @@ -2167,7 +2177,7 @@ namespace FourSlash { } ts.zipWith(expected, actual, (expectedClassification, actualClassification) => { - const expectedType: string = (ts.ClassificationTypeNames)[expectedClassification.classificationType]; + const expectedType = expectedClassification.classificationType; if (expectedType !== actualClassification.classificationType) { this.raiseError("verifyClassifications failed - expected classifications type to be " + expectedType + ", but was " + @@ -2347,7 +2357,8 @@ namespace FourSlash { private applyCodeAction(fileName: string, actions: ts.CodeAction[], index?: number): void { if (index === undefined) { if (!(actions && actions.length === 1)) { - this.raiseError(`Should find exactly one codefix, but ${actions ? actions.length : "none"} found.`); + const actionText = (actions && actions.length) ? JSON.stringify(actions) : "none"; + this.raiseError(`Should find exactly one codefix, but found ${actionText}`); } index = 0; } @@ -2701,6 +2712,60 @@ namespace FourSlash { } } + public verifyApplicableRefactorAvailableAtMarker(negative: boolean, markerName: string) { + const marker = this.getMarkerByName(markerName); + const applicableRefactors = this.languageService.getApplicableRefactors(this.activeFile.fileName, marker.position); + const isAvailable = applicableRefactors && applicableRefactors.length > 0; + if (negative && isAvailable) { + this.raiseError(`verifyApplicableRefactorAvailableAtMarker failed - expected no refactor at marker ${markerName} but found some.`); + } + if (!negative && !isAvailable) { + this.raiseError(`verifyApplicableRefactorAvailableAtMarker failed - expected a refactor at marker ${markerName} but found none.`); + } + } + + public verifyApplicableRefactorAvailableForRange(negative: boolean) { + const ranges = this.getRanges(); + if (!(ranges && ranges.length === 1)) { + throw new Error("Exactly one refactor range is allowed per test."); + } + + const applicableRefactors = this.languageService.getApplicableRefactors(this.activeFile.fileName, { pos: ranges[0].start, end: ranges[0].end }); + const isAvailable = applicableRefactors && applicableRefactors.length > 0; + if (negative && isAvailable) { + this.raiseError(`verifyApplicableRefactorAvailableForRange failed - expected no refactor but found some.`); + } + if (!negative && !isAvailable) { + this.raiseError(`verifyApplicableRefactorAvailableForRange failed - expected a refactor but found none.`); + } + } + + public verifyFileAfterApplyingRefactorAtMarker( + markerName: string, + expectedContent: string, + refactorNameToApply: string, + formattingOptions?: ts.FormatCodeSettings) { + + formattingOptions = formattingOptions || this.formatCodeSettings; + const markerPos = this.getMarkerByName(markerName).position; + + const applicableRefactors = this.languageService.getApplicableRefactors(this.activeFile.fileName, markerPos); + const applicableRefactorToApply = ts.find(applicableRefactors, refactor => refactor.name === refactorNameToApply); + + if (!applicableRefactorToApply) { + this.raiseError(`The expected refactor: ${refactorNameToApply} is not available at the marker location.`); + } + + const codeActions = this.languageService.getRefactorCodeActions(this.activeFile.fileName, formattingOptions, markerPos, refactorNameToApply); + + this.applyCodeAction(this.activeFile.fileName, codeActions); + const actualContent = this.getFileContent(this.activeFile.fileName); + + if (this.normalizeNewlines(actualContent) !== this.normalizeNewlines(expectedContent)) { + this.raiseError(`verifyFileAfterApplyingRefactors failed: expected:\n${expectedContent}\nactual:\n${actualContent}`); + } + } + public printAvailableCodeFixes() { const codeFixes = this.getCodeFixActions(this.activeFile.fileName); Harness.IO.log(stringify(codeFixes)); @@ -3417,6 +3482,18 @@ namespace FourSlashInterface { export class VerifyNegatable { public not: VerifyNegatable; + public allowedClassElementKeywords = [ + "public", + "private", + "protected", + "static", + "abstract", + "readonly", + "get", + "set", + "constructor", + "async" + ]; constructor(protected state: FourSlash.TestState, private negative = false) { if (!negative) { @@ -3453,6 +3530,12 @@ namespace FourSlashInterface { this.state.verifyCompletionListIsEmpty(this.negative); } + public completionListContainsClassElementKeywords() { + for (const keyword of this.allowedClassElementKeywords) { + this.completionListContains(keyword, keyword, /*documentation*/ undefined, "keyword"); + } + } + public completionListIsGlobal(expected: boolean) { this.state.verifyCompletionListIsGlobal(expected); } @@ -3496,6 +3579,14 @@ namespace FourSlashInterface { public codeFixAvailable() { this.state.verifyCodeFixAvailable(this.negative); } + + public applicableRefactorAvailableAtMarker(markerName: string) { + this.state.verifyApplicableRefactorAvailableAtMarker(this.negative, markerName); + } + + public applicableRefactorAvailableForRange() { + this.state.verifyApplicableRefactorAvailableForRange(this.negative); + } } export class Verify extends VerifyNegatable { @@ -3710,6 +3801,10 @@ namespace FourSlashInterface { this.state.verifyRangeAfterCodeFix(expectedText, includeWhiteSpace, errorCode, index); } + public fileAfterApplyingRefactorAtMarker(markerName: string, expectedContent: string, refactorNameToApply: string, formattingOptions?: ts.FormatCodeSettings): void { + this.state.verifyFileAfterApplyingRefactorAtMarker(markerName, expectedContent, refactorNameToApply, formattingOptions); + } + public importFixAtPosition(expectedTextArray: string[], errorCode?: number): void { this.state.verifyImportFixAtPosition(expectedTextArray, errorCode); } @@ -3784,7 +3879,7 @@ namespace FourSlashInterface { /** * This method *requires* an ordered stream of classifications for a file, and spans are highly recommended. */ - public semanticClassificationsAre(...classifications: { classificationType: string; text: string; textSpan?: FourSlash.TextSpan }[]) { + public semanticClassificationsAre(...classifications: Classification[]) { this.state.verifySemanticClassifications(classifications); } @@ -3979,102 +4074,107 @@ namespace FourSlashInterface { } } + interface Classification { + classificationType: ts.ClassificationTypeNames; + text: string; + textSpan?: FourSlash.TextSpan; + } export namespace Classification { - export function comment(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("comment", text, position); + export function comment(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.comment, text, position); } - export function identifier(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("identifier", text, position); + export function identifier(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.identifier, text, position); } - export function keyword(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("keyword", text, position); + export function keyword(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.keyword, text, position); } - export function numericLiteral(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("numericLiteral", text, position); + export function numericLiteral(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.numericLiteral, text, position); } - export function operator(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("operator", text, position); + export function operator(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.operator, text, position); } - export function stringLiteral(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("stringLiteral", text, position); + export function stringLiteral(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.stringLiteral, text, position); } - export function whiteSpace(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("whiteSpace", text, position); + export function whiteSpace(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.whiteSpace, text, position); } - export function text(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("text", text, position); + export function text(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.text, text, position); } - export function punctuation(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("punctuation", text, position); + export function punctuation(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.punctuation, text, position); } - export function docCommentTagName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("docCommentTagName", text, position); + export function docCommentTagName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.docCommentTagName, text, position); } - export function className(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("className", text, position); + export function className(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.className, text, position); } - export function enumName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("enumName", text, position); + export function enumName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.enumName, text, position); } - export function interfaceName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("interfaceName", text, position); + export function interfaceName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.interfaceName, text, position); } - export function moduleName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("moduleName", text, position); + export function moduleName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.moduleName, text, position); } - export function typeParameterName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("typeParameterName", text, position); + export function typeParameterName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.typeParameterName, text, position); } - export function parameterName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("parameterName", text, position); + export function parameterName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.parameterName, text, position); } - export function typeAliasName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("typeAliasName", text, position); + export function typeAliasName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.typeAliasName, text, position); } - export function jsxOpenTagName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("jsxOpenTagName", text, position); + export function jsxOpenTagName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.jsxOpenTagName, text, position); } - export function jsxCloseTagName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("jsxCloseTagName", text, position); + export function jsxCloseTagName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.jsxCloseTagName, text, position); } - export function jsxSelfClosingTagName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("jsxSelfClosingTagName", text, position); + export function jsxSelfClosingTagName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.jsxSelfClosingTagName, text, position); } - export function jsxAttribute(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("jsxAttribute", text, position); + export function jsxAttribute(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.jsxAttribute, text, position); } - export function jsxText(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("jsxText", text, position); + export function jsxText(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.jsxText, text, position); } - export function jsxAttributeStringLiteralValue(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("jsxAttributeStringLiteralValue", text, position); + export function jsxAttributeStringLiteralValue(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.jsxAttributeStringLiteralValue, text, position); } - function getClassification(type: string, text: string, position?: number) { + function getClassification(classificationType: ts.ClassificationTypeNames, text: string, position?: number): Classification { return { - classificationType: type, + classificationType, text: text, textSpan: position === undefined ? undefined : { start: position, end: position + text.length } }; diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 0dbc85cfc21..9bf4591112d 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -172,7 +172,7 @@ namespace Utils { assert.isFalse(child.pos < currentPos, "child.pos < currentPos"); currentPos = child.end; }, - (array: ts.NodeArray) => { + array => { assert.isFalse(array.pos < node.pos, "array.pos < node.pos"); assert.isFalse(array.end > node.end, "array.end > node.end"); assert.isFalse(array.pos < currentPos, "array.pos < currentPos"); @@ -383,7 +383,7 @@ namespace Utils { assertStructuralEquals(child1, child2); }, - (array1: ts.NodeArray) => { + array1 => { const childName = findChildName(node1, array1); const array2: ts.NodeArray = (node2)[childName]; @@ -1984,5 +1984,5 @@ namespace Harness { return { unitName: libFile, content: io.readFile(libFile) }; } - if (Error) (Error).stackTraceLimit = 1; + if (Error) (Error).stackTraceLimit = 100; } diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 3bf6f1cde9a..7aefb0f3a1f 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -489,6 +489,15 @@ namespace Harness.LanguageService { getCodeFixesAtPosition(): ts.CodeAction[] { throw new Error("Not supported on the shim."); } + getCodeFixDiagnostics(): ts.Diagnostic[] { + throw new Error("Not supported on the shim."); + } + getRefactorCodeActions(): ts.CodeAction[] { + throw new Error("Not supported on the shim."); + } + getApplicableRefactors(): ts.ApplicableRefactorInfo[] { + throw new Error("Not supported on the shim."); + } getEmitOutput(fileName: string): ts.EmitOutput { return unwrapJSONCallResult(this.shim.getEmitOutput(fileName)); } diff --git a/src/harness/projectsRunner.ts b/src/harness/projectsRunner.ts index b0efcf4c389..28d59fe35bd 100644 --- a/src/harness/projectsRunner.ts +++ b/src/harness/projectsRunner.ts @@ -372,7 +372,7 @@ class ProjectRunner extends RunnerBase { const compilerOptions = compilerResult.program.getCompilerOptions(); ts.forEach(compilerResult.program.getSourceFiles(), sourceFile => { - if (ts.isDeclarationFile(sourceFile)) { + if (sourceFile.isDeclarationFile) { allInputFiles.unshift({ emittedFileName: sourceFile.fileName, code: sourceFile.text }); } else if (!(compilerOptions.outFile || compilerOptions.out)) { diff --git a/src/harness/unittests/commandLineParsing.ts b/src/harness/unittests/commandLineParsing.ts index 6aa105e2c03..fc600bb55b4 100644 --- a/src/harness/unittests/commandLineParsing.ts +++ b/src/harness/unittests/commandLineParsing.ts @@ -60,7 +60,7 @@ namespace ts { assertParseResult(["--lib", "es5,invalidOption", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -263,7 +263,7 @@ namespace ts { assertParseResult(["--lib", "es5,", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -283,7 +283,7 @@ namespace ts { assertParseResult(["--lib", "es5, ", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, diff --git a/src/harness/unittests/convertCompilerOptionsFromJson.ts b/src/harness/unittests/convertCompilerOptionsFromJson.ts index cc0077aaa4e..2fe4ba83aff 100644 --- a/src/harness/unittests/convertCompilerOptionsFromJson.ts +++ b/src/harness/unittests/convertCompilerOptionsFromJson.ts @@ -233,7 +233,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -264,7 +264,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -295,7 +295,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -326,7 +326,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] diff --git a/src/harness/unittests/jsDocParsing.ts b/src/harness/unittests/jsDocParsing.ts index 98c32c77778..309e49bd6b8 100644 --- a/src/harness/unittests/jsDocParsing.ts +++ b/src/harness/unittests/jsDocParsing.ts @@ -241,6 +241,18 @@ namespace ts { */`); + parsesCorrectly("argSynonymForParamTag", +`/** + * @arg {number} name1 Description + */`); + + + parsesCorrectly("argumentSynonymForParamTag", +`/** + * @argument {number} name1 Description + */`); + + parsesCorrectly("templateTag", `/** * @template T diff --git a/src/harness/unittests/printer.ts b/src/harness/unittests/printer.ts index 0c6d4bfe8f7..a9af46b2780 100644 --- a/src/harness/unittests/printer.ts +++ b/src/harness/unittests/printer.ts @@ -98,8 +98,43 @@ namespace ts { ) ]) ); + + // https://github.com/Microsoft/TypeScript/issues/15971 + const classWithOptionalMethodAndProperty = createClassDeclaration( + undefined, + /* modifiers */ createNodeArray([createToken(SyntaxKind.DeclareKeyword)]), + /* name */ createIdentifier("X"), + undefined, + undefined, + createNodeArray([ + createMethod( + undefined, + undefined, + undefined, + /* name */ createIdentifier("method"), + /* questionToken */ createToken(SyntaxKind.QuestionToken), + undefined, + undefined, + /* type */ createKeywordTypeNode(SyntaxKind.VoidKeyword), + undefined + ), + createProperty( + undefined, + undefined, + /* name */ createIdentifier("property"), + /* questionToken */ createToken(SyntaxKind.QuestionToken), + /* type */ createKeywordTypeNode(SyntaxKind.StringKeyword), + undefined + ), + ]) + ); + // tslint:enable boolean-trivia printsCorrectly("class", {}, printer => printer.printNode(EmitHint.Unspecified, syntheticNode, sourceFile)); + + printsCorrectly("namespaceExportDeclaration", {}, printer => printer.printNode(EmitHint.Unspecified, createNamespaceExportDeclaration("B"), sourceFile)); + + printsCorrectly("classWithOptionalMethodAndProperty", {}, printer => printer.printNode(EmitHint.Unspecified, classWithOptionalMethodAndProperty, sourceFile)); }); }); } diff --git a/src/harness/unittests/services/preProcessFile.ts b/src/harness/unittests/services/preProcessFile.ts index 65f68b8ca25..6e77c27e4a8 100644 --- a/src/harness/unittests/services/preProcessFile.ts +++ b/src/harness/unittests/services/preProcessFile.ts @@ -37,8 +37,8 @@ describe("PreProcessFile:", function () { /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { - referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 37 }, { fileName: "refFile2.ts", pos: 38, end: 73 }, - { fileName: "refFile3.ts", pos: 74, end: 109 }, { fileName: "..\\refFile4d.ts", pos: 110, end: 150 }], + referencedFiles: [{ fileName: "refFile1.ts", pos: 22, end: 33 }, { fileName: "refFile2.ts", pos: 59, end: 70 }, + { fileName: "refFile3.ts", pos: 94, end: 105 }, { fileName: "..\\refFile4d.ts", pos: 131, end: 146 }], importedFiles: [], typeReferenceDirectives: [], ambientExternalModules: undefined, @@ -104,7 +104,7 @@ describe("PreProcessFile:", function () { /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { - referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 35 }, { fileName: "refFile2.ts", pos: 36, end: 71 }], + referencedFiles: [{ fileName: "refFile1.ts", pos: 20, end: 31 }, { fileName: "refFile2.ts", pos: 57, end: 68 }], typeReferenceDirectives: [], importedFiles: [{ fileName: "r1.ts", pos: 92, end: 97 }, { fileName: "r2.ts", pos: 121, end: 126 }], ambientExternalModules: undefined, @@ -117,7 +117,7 @@ describe("PreProcessFile:", function () { /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { - referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 35 }], + referencedFiles: [{ fileName: "refFile1.ts", pos: 20, end: 31 }], typeReferenceDirectives: [], importedFiles: [{ fileName: "r1.ts", pos: 91, end: 96 }, { fileName: "r3.ts", pos: 148, end: 153 }], ambientExternalModules: undefined, @@ -442,12 +442,12 @@ describe("PreProcessFile:", function () { /*detectJavaScriptImports*/ false, { referencedFiles: [ - { "pos": 13, "end": 38, "fileName": "a" }, - { "pos": 91, "end": 117, "fileName": "a2" } + { "pos": 34, "end": 35, "fileName": "a" }, + { "pos": 112, "end": 114, "fileName": "a2" } ], typeReferenceDirectives: [ - { "pos": 51, "end": 78, "fileName": "a1" }, - { "pos": 130, "end": 157, "fileName": "a3" } + { "pos": 73, "end": 75, "fileName": "a1" }, + { "pos": 152, "end": 154, "fileName": "a3" } ], importedFiles: [], ambientExternalModules: undefined, diff --git a/src/harness/unittests/session.ts b/src/harness/unittests/session.ts index a505c3ee7be..db33d87f087 100644 --- a/src/harness/unittests/session.ts +++ b/src/harness/unittests/session.ts @@ -134,7 +134,7 @@ namespace ts.server { type: "request", arguments: { formatOptions: { - indentStyle: "Block" + indentStyle: protocol.IndentStyle.Block, } } }; @@ -149,11 +149,11 @@ namespace ts.server { type: "request", arguments: { options: { - module: "System", - target: "ES5", - jsx: "React", - newLine: "Lf", - moduleResolution: "Node" + module: protocol.ModuleKind.System, + target: protocol.ScriptTarget.ES5, + jsx: protocol.JsxEmit.React, + newLine: protocol.NewLineKind.Lf, + moduleResolution: protocol.ModuleResolutionKind.Node, } } }; @@ -172,12 +172,81 @@ namespace ts.server { }); describe("onMessage", () => { + const allCommandNames: CommandNames[] = [ + CommandNames.Brace, + CommandNames.BraceFull, + CommandNames.BraceCompletion, + CommandNames.Change, + CommandNames.Close, + CommandNames.Completions, + CommandNames.CompletionsFull, + CommandNames.CompletionDetails, + CommandNames.CompileOnSaveAffectedFileList, + CommandNames.Configure, + CommandNames.Definition, + CommandNames.DefinitionFull, + CommandNames.Implementation, + CommandNames.ImplementationFull, + CommandNames.Exit, + CommandNames.Format, + CommandNames.Formatonkey, + CommandNames.FormatFull, + CommandNames.FormatonkeyFull, + CommandNames.FormatRangeFull, + CommandNames.Geterr, + CommandNames.GeterrForProject, + CommandNames.SemanticDiagnosticsSync, + CommandNames.SyntacticDiagnosticsSync, + CommandNames.NavBar, + CommandNames.NavBarFull, + CommandNames.Navto, + CommandNames.NavtoFull, + CommandNames.NavTree, + CommandNames.NavTreeFull, + CommandNames.Occurrences, + CommandNames.DocumentHighlights, + CommandNames.DocumentHighlightsFull, + CommandNames.Open, + CommandNames.Quickinfo, + CommandNames.QuickinfoFull, + CommandNames.References, + CommandNames.ReferencesFull, + CommandNames.Reload, + CommandNames.Rename, + CommandNames.RenameInfoFull, + CommandNames.RenameLocationsFull, + CommandNames.Saveto, + CommandNames.SignatureHelp, + CommandNames.SignatureHelpFull, + CommandNames.TypeDefinition, + CommandNames.ProjectInfo, + CommandNames.ReloadProjects, + CommandNames.Unknown, + CommandNames.OpenExternalProject, + CommandNames.CloseExternalProject, + CommandNames.SynchronizeProjectList, + CommandNames.ApplyChangedToOpenFiles, + CommandNames.EncodedSemanticClassificationsFull, + CommandNames.Cleanup, + CommandNames.OutliningSpans, + CommandNames.TodoComments, + CommandNames.Indentation, + CommandNames.DocCommentTemplate, + CommandNames.CompilerOptionsDiagnosticsFull, + CommandNames.NameOrDottedNameSpan, + CommandNames.BreakpointStatement, + CommandNames.CompilerOptionsForInferredProjects, + CommandNames.GetCodeFixes, + CommandNames.GetCodeFixesFull, + CommandNames.GetSupportedCodeFixes, + CommandNames.GetApplicableRefactors, + CommandNames.GetRefactorCodeActions, + CommandNames.GetRefactorCodeActionsFull, + ]; + it("should not throw when commands are executed with invalid arguments", () => { let i = 0; - for (const name in CommandNames) { - if (!Object.prototype.hasOwnProperty.call(CommandNames, name)) { - continue; - } + for (const name of allCommandNames) { const req: protocol.Request = { command: name, seq: i, diff --git a/src/harness/unittests/tsserverProjectSystem.ts b/src/harness/unittests/tsserverProjectSystem.ts index 33838b5805f..efa92490300 100644 --- a/src/harness/unittests/tsserverProjectSystem.ts +++ b/src/harness/unittests/tsserverProjectSystem.ts @@ -337,6 +337,7 @@ namespace ts.projectSystem { this.map[timeoutId] = cb.bind(/*this*/ undefined, ...args); return timeoutId; } + unregister(id: any) { if (typeof id === "number") { delete this.map[id]; @@ -352,10 +353,13 @@ namespace ts.projectSystem { } invoke() { + // Note: invoking a callback may result in new callbacks been queued, + // so do not clear the entire callback list regardless. Only remove the + // ones we have invoked. for (const key in this.map) { this.map[key](); + delete this.map[key]; } - this.map = []; } } @@ -3743,7 +3747,7 @@ namespace ts.projectSystem { // run first step host.runQueuedTimeoutCallbacks(); - assert.equal(host.getOutput().length, 1, "expect 1 messages"); + assert.equal(host.getOutput().length, 1, "expect 1 message"); const e1 = getMessage(0); assert.equal(e1.event, "syntaxDiag"); host.clearOutput(); @@ -3765,11 +3769,12 @@ namespace ts.projectSystem { // run first step host.runQueuedTimeoutCallbacks(); - assert.equal(host.getOutput().length, 1, "expect 1 messages"); + assert.equal(host.getOutput().length, 1, "expect 1 message"); const e1 = getMessage(0); assert.equal(e1.event, "syntaxDiag"); host.clearOutput(); + // the semanticDiag message host.runQueuedImmediateCallbacks(); assert.equal(host.getOutput().length, 2, "expect 2 messages"); const e2 = getMessage(0); @@ -3787,7 +3792,7 @@ namespace ts.projectSystem { assert.equal(host.getOutput().length, 0, "expect 0 messages"); // run first step host.runQueuedTimeoutCallbacks(); - assert.equal(host.getOutput().length, 1, "expect 1 messages"); + assert.equal(host.getOutput().length, 1, "expect 1 message"); const e1 = getMessage(0); assert.equal(e1.event, "syntaxDiag"); host.clearOutput(); diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index c43c59e3b12..3aa813c0a8a 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -1,14 +1,14 @@ ///////////////////////////// -/// IE DOM APIs +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -21,32 +21,32 @@ interface AnimationEventInit extends EventInit { } interface AssertionOptions { - timeoutSeconds?: number; - rpId?: USVString; allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface CacheQueryOptions { - ignoreSearch?: boolean; - ignoreMethod?: boolean; - ignoreVary?: boolean; cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; } interface ClientData { challenge?: string; + extensions?: WebAuthnExtensions; + hashAlg?: string | Algorithm; origin?: string; rpId?: string; - hashAlg?: string | Algorithm; tokenBinding?: string; - extensions?: WebAuthnExtensions; } interface CloseEventInit extends EventInit { - wasClean?: boolean; code?: number; reason?: string; + wasClean?: boolean; } interface CompositionEventInit extends UIEventInit { @@ -86,13 +86,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -106,15 +99,15 @@ interface DeviceLightEventInit extends EventInit { interface DeviceMotionEventInit extends EventInit { acceleration?: DeviceAccelerationDict; accelerationIncludingGravity?: DeviceAccelerationDict; - rotationRate?: DeviceRotationRateDict; interval?: number; + rotationRate?: DeviceRotationRateDict; } interface DeviceOrientationEventInit extends EventInit { + absolute?: boolean; alpha?: number; beta?: number; gamma?: number; - absolute?: boolean; } interface DeviceRotationRateDict { @@ -123,17 +116,24 @@ interface DeviceRotationRateDict { gamma?: number; } +interface DOMRectInit { + height?: any; + width?: any; + x?: any; + y?: any; +} + interface DoubleRange { max?: number; min?: number; } interface ErrorEventInit extends EventInit { - message?: string; - filename?: string; - lineno?: number; colno?: number; error?: any; + filename?: string; + lineno?: number; + message?: string; } interface EventInit { @@ -143,9 +143,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -158,6 +157,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -170,17 +170,17 @@ interface FocusEventInit extends UIEventInit { interface FocusNavigationEventInit extends EventInit { navigationReason?: string; + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface FocusNavigationOrigin { + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface GamepadEventInit extends EventInit { @@ -207,11 +207,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -236,39 +236,153 @@ interface LongRange { min?: number; } +interface MediaEncryptedEventInit extends EventInit { + initData?: ArrayBuffer; + initDataType?: string; +} + +interface MediaKeyMessageEventInit extends EventInit { + message?: ArrayBuffer; + messageType?: MediaKeyMessageType; +} + +interface MediaKeySystemConfiguration { + audioCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: MediaKeysRequirement; + initDataTypes?: string[]; + persistentState?: MediaKeysRequirement; + videoCapabilities?: MediaKeySystemMediaCapability[]; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + robustness?: string; +} + +interface MediaStreamConstraints { + audio?: boolean | MediaTrackConstraints; + video?: boolean | MediaTrackConstraints; +} + +interface MediaStreamErrorEventInit extends EventInit { + error?: MediaStreamError; +} + +interface MediaStreamEventInit extends EventInit { + stream?: MediaStream; +} + +interface MediaStreamTrackEventInit extends EventInit { + track?: MediaStreamTrack; +} + +interface MediaTrackCapabilities { + aspectRatio?: number | DoubleRange; + deviceId?: string; + echoCancellation?: boolean[]; + facingMode?: string; + frameRate?: number | DoubleRange; + groupId?: string; + height?: number | LongRange; + sampleRate?: number | LongRange; + sampleSize?: number | LongRange; + volume?: number | DoubleRange; + width?: number | LongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + echoCancelation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackSettings { + aspectRatio?: number; + deviceId?: string; + echoCancellation?: boolean; + facingMode?: string; + frameRate?: number; + groupId?: string; + height?: number; + sampleRate?: number; + sampleSize?: number; + volume?: number; + width?: number; +} + +interface MediaTrackSupportedConstraints { + aspectRatio?: boolean; + deviceId?: boolean; + echoCancellation?: boolean; + facingMode?: boolean; + frameRate?: boolean; + groupId?: boolean; + height?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + volume?: boolean; + width?: boolean; +} + +interface MessageEventInit extends EventInit { + lastEventId?: string; + channel?: string; + data?: any; + origin?: string; + ports?: MessagePort[]; + source?: Window; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget; + screenX?: number; + screenY?: number; +} + interface MSAccountInfo { + accountImageUri?: string; + accountName?: string; rpDisplayName?: string; userDisplayName?: string; - accountName?: string; userId?: string; - accountImageUri?: string; } interface MSAudioLocalClientEvent extends MSLocalClientEventBase { - networkSendQualityEventRatio?: number; - networkDelayEventRatio?: number; cpuInsufficientEventRatio?: number; - deviceHalfDuplexAECEventRatio?: number; - deviceRenderNotFunctioningEventRatio?: number; deviceCaptureNotFunctioningEventRatio?: number; - deviceGlitchesEventRatio?: number; - deviceLowSNREventRatio?: number; - deviceLowSpeechLevelEventRatio?: number; deviceClippingEventRatio?: number; deviceEchoEventRatio?: number; - deviceNearEndToEchoRatioEventRatio?: number; - deviceRenderZeroVolumeEventRatio?: number; - deviceRenderMuteEventRatio?: number; - deviceMultipleEndpointsEventCount?: number; + deviceGlitchesEventRatio?: number; + deviceHalfDuplexAECEventRatio?: number; deviceHowlingEventCount?: number; + deviceLowSNREventRatio?: number; + deviceLowSpeechLevelEventRatio?: number; + deviceMultipleEndpointsEventCount?: number; + deviceNearEndToEchoRatioEventRatio?: number; + deviceRenderMuteEventRatio?: number; + deviceRenderNotFunctioningEventRatio?: number; + deviceRenderZeroVolumeEventRatio?: number; + networkDelayEventRatio?: number; + networkSendQualityEventRatio?: number; } interface MSAudioRecvPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioRecvSignal; - packetReorderRatio?: number; - packetReorderDepthAvg?: number; - packetReorderDepthMax?: number; burstLossLength1?: number; burstLossLength2?: number; burstLossLength3?: number; @@ -280,31 +394,36 @@ interface MSAudioRecvPayload extends MSPayloadBase { fecRecvDistance1?: number; fecRecvDistance2?: number; fecRecvDistance3?: number; + packetReorderDepthAvg?: number; + packetReorderDepthMax?: number; + packetReorderRatio?: number; + ratioCompressedSamplesAvg?: number; ratioConcealedSamplesAvg?: number; ratioStretchedSamplesAvg?: number; - ratioCompressedSamplesAvg?: number; + samplingRate?: number; + signal?: MSAudioRecvSignal; } interface MSAudioRecvSignal { initialSignalLevelRMS?: number; - recvSignalLevelCh1?: number; recvNoiseLevelCh1?: number; - renderSignalLevel?: number; - renderNoiseLevel?: number; + recvSignalLevelCh1?: number; renderLoopbackSignalLevel?: number; + renderNoiseLevel?: number; + renderSignalLevel?: number; } interface MSAudioSendPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioSendSignal; audioFECUsed?: boolean; + samplingRate?: number; sendMutePercent?: number; + signal?: MSAudioSendSignal; } interface MSAudioSendSignal { noiseLevel?: number; - sendSignalLevelCh1?: number; sendNoiseLevelCh1?: number; + sendSignalLevelCh1?: number; } interface MSConnectivity { @@ -322,8 +441,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -333,12 +452,12 @@ interface MSDelay { interface MSDescription extends RTCStats { connectivity?: MSConnectivity; - transport?: RTCIceProtocol; - networkconnectivity?: MSNetworkConnectivityInfo; - localAddr?: MSIPAddressInfo; - remoteAddr?: MSIPAddressInfo; deviceDevName?: string; + localAddr?: MSIPAddressInfo; + networkconnectivity?: MSNetworkConnectivityInfo; reflexiveLocalIPAddr?: MSIPAddressInfo; + remoteAddr?: MSIPAddressInfo; + transport?: RTCIceProtocol; } interface MSFIDOCredentialParameters extends MSCredentialParameters { @@ -346,35 +465,35 @@ interface MSFIDOCredentialParameters extends MSCredentialParameters { authenticators?: AAGUID[]; } -interface MSIPAddressInfo { - ipAddr?: string; - port?: number; - manufacturerMacAddrMask?: string; -} - interface MSIceWarningFlags { - turnTcpTimedOut?: boolean; - turnUdpAllocateFailed?: boolean; - turnUdpSendFailed?: boolean; + allocationMessageIntegrityFailed?: boolean; + alternateServerReceived?: boolean; + connCheckMessageIntegrityFailed?: boolean; + connCheckOtherError?: boolean; + fipsAllocationFailure?: boolean; + multipleRelayServersAttempted?: boolean; + noRelayServersConfigured?: boolean; + portRangeExhausted?: boolean; + pseudoTLSFailure?: boolean; + tcpNatConnectivityFailed?: boolean; + tcpRelayConnectivityFailed?: boolean; + turnAuthUnknownUsernameError?: boolean; turnTcpAllocateFailed?: boolean; turnTcpSendFailed?: boolean; + turnTcpTimedOut?: boolean; + turnTurnTcpConnectivityFailed?: boolean; + turnUdpAllocateFailed?: boolean; + turnUdpSendFailed?: boolean; udpLocalConnectivityFailed?: boolean; udpNatConnectivityFailed?: boolean; udpRelayConnectivityFailed?: boolean; - tcpNatConnectivityFailed?: boolean; - tcpRelayConnectivityFailed?: boolean; - connCheckMessageIntegrityFailed?: boolean; - allocationMessageIntegrityFailed?: boolean; - connCheckOtherError?: boolean; - turnAuthUnknownUsernameError?: boolean; - noRelayServersConfigured?: boolean; - multipleRelayServersAttempted?: boolean; - portRangeExhausted?: boolean; - alternateServerReceived?: boolean; - pseudoTLSFailure?: boolean; - turnTurnTcpConnectivityFailed?: boolean; useCandidateChecksFailed?: boolean; - fipsAllocationFailure?: boolean; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSJitter { @@ -384,28 +503,28 @@ interface MSJitter { } interface MSLocalClientEventBase extends RTCStats { - networkReceiveQualityEventRatio?: number; networkBandwidthLowEventRatio?: number; + networkReceiveQualityEventRatio?: number; } interface MSNetwork extends RTCStats { - jitter?: MSJitter; delay?: MSDelay; + jitter?: MSJitter; packetLoss?: MSPacketLoss; utilization?: MSUtilization; } interface MSNetworkConnectivityInfo { - vpn?: boolean; linkspeed?: number; networkConnectionDetails?: string; + vpn?: boolean; } interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; - interfaceTypeWireless?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; + interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; } @@ -423,13 +542,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -437,241 +556,122 @@ interface MSSignatureParameters { } interface MSTransportDiagnosticsStats extends RTCStats { - baseAddress?: string; - localAddress?: string; - localSite?: string; - networkName?: string; - remoteAddress?: string; - remoteSite?: string; - localMR?: string; - remoteMR?: string; - iceWarningFlags?: MSIceWarningFlags; - portRangeMin?: number; - portRangeMax?: number; - localMRTCPPort?: number; - remoteMRTCPPort?: number; - stunVer?: number; - numConsentReqSent?: number; - numConsentReqReceived?: number; - numConsentRespSent?: number; - numConsentRespReceived?: number; - interfaces?: MSNetworkInterfaceType; - baseInterface?: MSNetworkInterfaceType; - protocol?: RTCIceProtocol; - localInterface?: MSNetworkInterfaceType; - localAddrType?: MSIceAddrType; - remoteAddrType?: MSIceAddrType; - iceRole?: RTCIceRole; - rtpRtcpMux?: boolean; allocationTimeInMs?: number; + baseAddress?: string; + baseInterface?: MSNetworkInterfaceType; + iceRole?: RTCIceRole; + iceWarningFlags?: MSIceWarningFlags; + interfaces?: MSNetworkInterfaceType; + localAddress?: string; + localAddrType?: MSIceAddrType; + localInterface?: MSNetworkInterfaceType; + localMR?: string; + localMRTCPPort?: number; + localSite?: string; msRtcEngineVersion?: string; + networkName?: string; + numConsentReqReceived?: number; + numConsentReqSent?: number; + numConsentRespReceived?: number; + numConsentRespSent?: number; + portRangeMax?: number; + portRangeMin?: number; + protocol?: RTCIceProtocol; + remoteAddress?: string; + remoteAddrType?: MSIceAddrType; + remoteMR?: string; + remoteMRTCPPort?: number; + remoteSite?: string; + rtpRtcpMux?: boolean; + stunVer?: number; } interface MSUtilization { - packets?: number; bandwidthEstimation?: number; - bandwidthEstimationMin?: number; - bandwidthEstimationMax?: number; - bandwidthEstimationStdDev?: number; bandwidthEstimationAvg?: number; + bandwidthEstimationMax?: number; + bandwidthEstimationMin?: number; + bandwidthEstimationStdDev?: number; + packets?: number; } interface MSVideoPayload extends MSPayloadBase { + durationSeconds?: number; resolution?: string; videoBitRateAvg?: number; videoBitRateMax?: number; videoFrameRateAvg?: number; videoPacketLossRate?: number; - durationSeconds?: number; } interface MSVideoRecvPayload extends MSVideoPayload { - videoFrameLossRate?: number; - recvCodecType?: string; - recvResolutionWidth?: number; - recvResolutionHeight?: number; - videoResolutions?: MSVideoResolutionDistribution; - recvFrameRateAverage?: number; - recvBitRateMaximum?: number; + lowBitRateCallPercent?: number; + lowFrameRateCallPercent?: number; recvBitRateAverage?: number; + recvBitRateMaximum?: number; + recvCodecType?: string; + recvFpsHarmonicAverage?: number; + recvFrameRateAverage?: number; + recvNumResSwitches?: number; + recvReorderBufferMaxSuccessfullyOrderedExtent?: number; + recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; + recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; + recvReorderBufferPacketsDroppedDueToTimeout?: number; + recvReorderBufferReorderedPackets?: number; + recvResolutionHeight?: number; + recvResolutionWidth?: number; recvVideoStreamsMax?: number; recvVideoStreamsMin?: number; recvVideoStreamsMode?: number; - videoPostFECPLR?: number; - lowBitRateCallPercent?: number; - lowFrameRateCallPercent?: number; reorderBufferTotalPackets?: number; - recvReorderBufferReorderedPackets?: number; - recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; - recvReorderBufferMaxSuccessfullyOrderedExtent?: number; - recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; - recvReorderBufferPacketsDroppedDueToTimeout?: number; - recvFpsHarmonicAverage?: number; - recvNumResSwitches?: number; + videoFrameLossRate?: number; + videoPostFECPLR?: number; + videoResolutions?: MSVideoResolutionDistribution; } interface MSVideoResolutionDistribution { cifQuality?: number; - vgaQuality?: number; - h720Quality?: number; h1080Quality?: number; h1440Quality?: number; h2160Quality?: number; + h720Quality?: number; + vgaQuality?: number; } interface MSVideoSendPayload extends MSVideoPayload { - sendFrameRateAverage?: number; - sendBitRateMaximum?: number; sendBitRateAverage?: number; - sendVideoStreamsMax?: number; - sendResolutionWidth?: number; + sendBitRateMaximum?: number; + sendFrameRateAverage?: number; sendResolutionHeight?: number; -} - -interface MediaEncryptedEventInit extends EventInit { - initDataType?: string; - initData?: ArrayBuffer; -} - -interface MediaKeyMessageEventInit extends EventInit { - messageType?: MediaKeyMessageType; - message?: ArrayBuffer; -} - -interface MediaKeySystemConfiguration { - initDataTypes?: string[]; - audioCapabilities?: MediaKeySystemMediaCapability[]; - videoCapabilities?: MediaKeySystemMediaCapability[]; - distinctiveIdentifier?: MediaKeysRequirement; - persistentState?: MediaKeysRequirement; -} - -interface MediaKeySystemMediaCapability { - contentType?: string; - robustness?: string; -} - -interface MediaStreamConstraints { - video?: boolean | MediaTrackConstraints; - audio?: boolean | MediaTrackConstraints; -} - -interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; -} - -interface MediaStreamEventInit extends EventInit { - stream?: MediaStream; -} - -interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; -} - -interface MediaTrackCapabilities { - width?: number | LongRange; - height?: number | LongRange; - aspectRatio?: number | DoubleRange; - frameRate?: number | DoubleRange; - facingMode?: string; - volume?: number | DoubleRange; - sampleRate?: number | LongRange; - sampleSize?: number | LongRange; - echoCancellation?: boolean[]; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackConstraintSet { - width?: number | ConstrainLongRange; - height?: number | ConstrainLongRange; - aspectRatio?: number | ConstrainDoubleRange; - frameRate?: number | ConstrainDoubleRange; - facingMode?: string | string[] | ConstrainDOMStringParameters; - volume?: number | ConstrainDoubleRange; - sampleRate?: number | ConstrainLongRange; - sampleSize?: number | ConstrainLongRange; - echoCancelation?: boolean | ConstrainBooleanParameters; - deviceId?: string | string[] | ConstrainDOMStringParameters; - groupId?: string | string[] | ConstrainDOMStringParameters; -} - -interface MediaTrackConstraints extends MediaTrackConstraintSet { - advanced?: MediaTrackConstraintSet[]; -} - -interface MediaTrackSettings { - width?: number; - height?: number; - aspectRatio?: number; - frameRate?: number; - facingMode?: string; - volume?: number; - sampleRate?: number; - sampleSize?: number; - echoCancellation?: boolean; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackSupportedConstraints { - width?: boolean; - height?: boolean; - aspectRatio?: boolean; - frameRate?: boolean; - facingMode?: boolean; - volume?: boolean; - sampleRate?: boolean; - sampleSize?: boolean; - echoCancellation?: boolean; - deviceId?: boolean; - groupId?: boolean; -} - -interface MessageEventInit extends EventInit { - lastEventId?: string; - channel?: string; - data?: any; - origin?: string; - source?: Window; - ports?: MessagePort[]; -} - -interface MouseEventInit extends EventModifierInit { - screenX?: number; - screenY?: number; - clientX?: number; - clientY?: number; - button?: number; - buttons?: number; - relatedTarget?: EventTarget; + sendResolutionWidth?: number; + sendVideoStreamsMax?: number; } interface MsZoomToOptions { + animate?: string; contentX?: number; contentY?: number; + scaleFactor?: number; viewportX?: string; viewportY?: string; - scaleFactor?: number; - animate?: string; } interface MutationObserverInit { - childList?: boolean; + attributeFilter?: string[]; + attributeOldValue?: boolean; attributes?: boolean; characterData?: boolean; - subtree?: boolean; - attributeOldValue?: boolean; characterDataOldValue?: boolean; - attributeFilter?: string[]; + childList?: boolean; + subtree?: boolean; } interface NotificationOptions { - dir?: NotificationDirection; - lang?: string; body?: string; - tag?: string; + dir?: NotificationDirection; icon?: string; + lang?: string; + tag?: string; } interface ObjectURLOptions { @@ -680,39 +680,39 @@ interface ObjectURLOptions { interface PaymentCurrencyAmount { currency?: string; - value?: string; currencySystem?: string; + value?: string; } interface PaymentDetails { - total?: PaymentItem; displayItems?: PaymentItem[]; - shippingOptions?: PaymentShippingOption[]; - modifiers?: PaymentDetailsModifier[]; error?: string; + modifiers?: PaymentDetailsModifier[]; + shippingOptions?: PaymentShippingOption[]; + total?: PaymentItem; } interface PaymentDetailsModifier { - supportedMethods?: string[]; - total?: PaymentItem; additionalDisplayItems?: PaymentItem[]; data?: any; + supportedMethods?: string[]; + total?: PaymentItem; } interface PaymentItem { - label?: string; amount?: PaymentCurrencyAmount; + label?: string; pending?: boolean; } interface PaymentMethodData { - supportedMethods?: string[]; data?: any; + supportedMethods?: string[]; } interface PaymentOptions { - requestPayerName?: boolean; requestPayerEmail?: boolean; + requestPayerName?: boolean; requestPayerPhone?: boolean; requestShipping?: boolean; shippingType?: string; @@ -722,9 +722,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -733,14 +733,14 @@ interface PeriodicWaveConstraints { } interface PointerEventInit extends MouseEventInit { - pointerId?: number; - width?: number; height?: number; + isPrimary?: boolean; + pointerId?: number; + pointerType?: string; pressure?: number; tiltX?: number; tiltY?: number; - pointerType?: string; - isPrimary?: boolean; + width?: number; } interface PopStateEventInit extends EventInit { @@ -749,8 +749,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -760,38 +760,63 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - userVisibleOnly?: boolean; applicationServerKey?: any; + userVisibleOnly?: boolean; +} + +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: any; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: any; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + window?: any; +} + +interface ResponseInit { + headers?: any; + status?: number; + statusText?: string; } interface RTCConfiguration { + bundlePolicy?: RTCBundlePolicy; iceServers?: RTCIceServer[]; iceTransportPolicy?: RTCIceTransportPolicy; - bundlePolicy?: RTCBundlePolicy; peerIdentity?: string; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCDtlsFingerprint { algorithm?: string; value?: string; } interface RTCDtlsParameters { - role?: RTCDtlsRole; fingerprints?: RTCDtlsFingerprint[]; + role?: RTCDtlsRole; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; } interface RTCIceCandidateAttributes extends RTCStats { + addressSourceUrl?: string; + candidateType?: RTCStatsIceCandidateType; ipAddress?: string; portNumber?: number; - transport?: string; - candidateType?: RTCStatsIceCandidateType; priority?: number; - addressSourceUrl?: string; + transport?: string; } interface RTCIceCandidateComplete { @@ -799,15 +824,15 @@ interface RTCIceCandidateComplete { interface RTCIceCandidateDictionary { foundation?: string; - priority?: number; ip?: string; - protocol?: RTCIceProtocol; + msMTurnSessionId?: string; port?: number; - type?: RTCIceCandidateType; - tcpType?: RTCIceTcpCandidateType; + priority?: number; + protocol?: RTCIceProtocol; relatedAddress?: string; relatedPort?: number; - msMTurnSessionId?: string; + tcpType?: RTCIceTcpCandidateType; + type?: RTCIceCandidateType; } interface RTCIceCandidateInit { @@ -822,19 +847,19 @@ interface RTCIceCandidatePair { } interface RTCIceCandidatePairStats extends RTCStats { - transportId?: string; - localCandidateId?: string; - remoteCandidateId?: string; - state?: RTCStatsIceCandidatePairState; - priority?: number; - nominated?: boolean; - writable?: boolean; - readable?: boolean; - bytesSent?: number; - bytesReceived?: number; - roundTripTime?: number; - availableOutgoingBitrate?: number; availableIncomingBitrate?: number; + availableOutgoingBitrate?: number; + bytesReceived?: number; + bytesSent?: number; + localCandidateId?: string; + nominated?: boolean; + priority?: number; + readable?: boolean; + remoteCandidateId?: string; + roundTripTime?: number; + state?: RTCStatsIceCandidatePairState; + transportId?: string; + writable?: boolean; } interface RTCIceGatherOptions { @@ -844,285 +869,260 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - usernameFragment?: string; - password?: string; iceLite?: boolean; + password?: string; + usernameFragment?: string; } interface RTCIceServer { + credential?: string; urls?: any; username?: string; - credential?: string; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { - packetsReceived?: number; bytesReceived?: number; - packetsLost?: number; - jitter?: number; fractionLost?: number; + jitter?: number; + packetsLost?: number; + packetsReceived?: number; } interface RTCMediaStreamTrackStats extends RTCStats { - trackIdentifier?: string; - remoteSource?: boolean; - ssrcIds?: string[]; - frameWidth?: number; - frameHeight?: number; - framesPerSecond?: number; - framesSent?: number; - framesReceived?: number; - framesDecoded?: number; - framesDropped?: number; - framesCorrupted?: number; audioLevel?: number; echoReturnLoss?: number; echoReturnLossEnhancement?: number; + frameHeight?: number; + framesCorrupted?: number; + framesDecoded?: number; + framesDropped?: number; + framesPerSecond?: number; + framesReceived?: number; + framesSent?: number; + frameWidth?: number; + remoteSource?: boolean; + ssrcIds?: string[]; + trackIdentifier?: string; } interface RTCOfferOptions { - offerToReceiveVideo?: number; - offerToReceiveAudio?: number; - voiceActivityDetection?: boolean; iceRestart?: boolean; + offerToReceiveAudio?: number; + offerToReceiveVideo?: number; + voiceActivityDetection?: boolean; } interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { - packetsSent?: number; bytesSent?: number; - targetBitrate?: number; + packetsSent?: number; roundTripTime?: number; + targetBitrate?: number; } interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } -interface RTCRTPStreamStats extends RTCStats { - ssrc?: string; - associateStatsId?: string; - isRemote?: boolean; - mediaTrackId?: string; - transportId?: string; - codecId?: string; - firCount?: number; - pliCount?: number; - nackCount?: number; - sliCount?: number; -} - interface RTCRtcpFeedback { - type?: string; parameter?: string; + type?: string; } interface RTCRtcpParameters { - ssrc?: number; cname?: string; - reducedSize?: boolean; mux?: boolean; + reducedSize?: boolean; + ssrc?: number; } interface RTCRtpCapabilities { codecs?: RTCRtpCodecCapability[]; - headerExtensions?: RTCRtpHeaderExtension[]; fecMechanisms?: string[]; + headerExtensions?: RTCRtpHeaderExtension[]; } interface RTCRtpCodecCapability { - name?: string; - kind?: string; clockRate?: number; - preferredPayloadType?: number; + kind?: string; maxptime?: number; - ptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; - options?: any; - maxTemporalLayers?: number; maxSpatialLayers?: number; + maxTemporalLayers?: number; + name?: string; + numChannels?: number; + options?: any; + parameters?: any; + preferredPayloadType?: number; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; svcMultiStreamSupport?: boolean; } interface RTCRtpCodecParameters { - name?: string; - payloadType?: any; clockRate?: number; maxptime?: number; - ptime?: number; + name?: string; numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; parameters?: any; + payloadType?: any; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; } interface RTCRtpContributingSource { - timestamp?: number; - csrc?: number; audioLevel?: number; + csrc?: number; + timestamp?: number; } interface RTCRtpEncodingParameters { - ssrc?: number; - codecPayloadType?: number; - fec?: RTCRtpFecParameters; - rtx?: RTCRtpRtxParameters; - priority?: number; - maxBitrate?: number; - minQuality?: number; - resolutionScale?: number; - framerateScale?: number; - maxFramerate?: number; active?: boolean; - encodingId?: string; + codecPayloadType?: number; dependencyEncodingIds?: string[]; + encodingId?: string; + fec?: RTCRtpFecParameters; + framerateScale?: number; + maxBitrate?: number; + maxFramerate?: number; + minQuality?: number; + priority?: number; + resolutionScale?: number; + rtx?: RTCRtpRtxParameters; + ssrc?: number; ssrcRange?: RTCSsrcRange; } interface RTCRtpFecParameters { - ssrc?: number; mechanism?: string; + ssrc?: number; } interface RTCRtpHeaderExtension { kind?: string; - uri?: string; - preferredId?: number; preferredEncrypt?: boolean; + preferredId?: number; + uri?: string; } interface RTCRtpHeaderExtensionParameters { - uri?: string; - id?: number; encrypt?: boolean; + id?: number; + uri?: string; } interface RTCRtpParameters { - muxId?: string; codecs?: RTCRtpCodecParameters[]; - headerExtensions?: RTCRtpHeaderExtensionParameters[]; - encodings?: RTCRtpEncodingParameters[]; - rtcp?: RTCRtcpParameters; degradationPreference?: RTCDegradationPreference; + encodings?: RTCRtpEncodingParameters[]; + headerExtensions?: RTCRtpHeaderExtensionParameters[]; + muxId?: string; + rtcp?: RTCRtcpParameters; } interface RTCRtpRtxParameters { ssrc?: number; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtpUnhandled { - ssrc?: number; - payloadType?: number; muxId?: string; + payloadType?: number; + ssrc?: number; } interface RTCSessionDescriptionInit { - type?: RTCSdpType; sdp?: string; + type?: RTCSdpType; } interface RTCSrtpKeyParam { keyMethod?: string; keySalt?: string; lifetime?: string; - mkiValue?: number; mkiLength?: number; + mkiValue?: number; } interface RTCSrtpSdesParameters { - tag?: number; cryptoSuite?: string; keyParams?: RTCSrtpKeyParam[]; sessionParams?: string[]; + tag?: number; } interface RTCSsrcRange { - min?: number; max?: number; + min?: number; } interface RTCStats { - timestamp?: number; - type?: RTCStatsType; id?: string; msType?: MSStatsType; + timestamp?: number; + type?: RTCStatsType; } interface RTCStatsReport { } interface RTCTransportStats extends RTCStats { - bytesSent?: number; - bytesReceived?: number; - rtcpTransportStatsId?: string; activeConnection?: boolean; - selectedCandidatePairId?: string; + bytesReceived?: number; + bytesSent?: number; localCertificateId?: string; remoteCertificateId?: string; -} - -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - method?: string; - headers?: any; - body?: any; - referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode?: RequestMode; - credentials?: RequestCredentials; - cache?: RequestCache; - redirect?: RequestRedirect; - integrity?: string; - keepalive?: boolean; - window?: any; -} - -interface ResponseInit { - status?: number; - statusText?: string; - headers?: any; + rtcpTransportStatsId?: string; + selectedCandidatePairId?: string; } interface ScopedCredentialDescriptor { - type?: ScopedCredentialType; id?: any; transports?: Transport[]; + type?: ScopedCredentialType; } interface ScopedCredentialOptions { - timeoutSeconds?: number; - rpId?: USVString; excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface ScopedCredentialParameters { - type?: ScopedCredentialType; algorithm?: string | Algorithm; + type?: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; - origin?: string; lastEventId?: string; - source?: ServiceWorker | MessagePort; + origin?: string; ports?: MessagePort[]; + source?: ServiceWorker | MessagePort; } interface SpeechSynthesisEventInit extends EventInit { - utterance?: SpeechSynthesisUtterance; charIndex?: number; elapsedTime?: number; name?: string; + utterance?: SpeechSynthesisUtterance; } interface StoreExceptionsInformation extends ExceptionInformation { - siteName?: string; - explanationString?: string; detailURI?: string; + explanationString?: string; + siteName?: string; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -1134,13 +1134,13 @@ interface TrackEventInit extends EventInit { } interface TransitionEventInit extends EventInit { - propertyName?: string; elapsedTime?: number; + propertyName?: string; } interface UIEventInit extends EventInit { - view?: Window; detail?: number; + view?: Window; } interface WebAuthnExtensions { @@ -1149,11 +1149,11 @@ interface WebAuthnExtensions { interface WebGLContextAttributes { failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; - depth?: boolean; - stencil?: boolean; antialias?: boolean; + depth?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; + stencil?: boolean; } interface WebGLContextEventInit extends EventInit { @@ -1161,10 +1161,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -1183,19 +1183,6 @@ interface WebKitFileCallback { (evt: Event): void; } -interface ANGLE_instanced_arrays { - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -1211,8 +1198,21 @@ interface AnalyserNode extends AudioNode { declare var AnalyserNode: { prototype: AnalyserNode; new(): AnalyserNode; +}; + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; + drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; + vertexAttribDivisorANGLE(index: number, divisor: number): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; } +declare var ANGLE_instanced_arrays: { + prototype: ANGLE_instanced_arrays; + new(): ANGLE_instanced_arrays; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +}; + interface AnimationEvent extends Event { readonly animationName: string; readonly elapsedTime: number; @@ -1222,7 +1222,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -1267,7 +1267,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -1280,7 +1280,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -1295,7 +1295,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -1318,7 +1318,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -1364,7 +1364,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -1373,7 +1373,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -1386,7 +1386,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -1405,7 +1405,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -1421,7 +1421,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -1432,7 +1432,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -1446,7 +1446,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -1469,7 +1469,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -1478,7 +1478,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -1487,13 +1487,13 @@ interface BeforeUnloadEvent extends Event { declare var BeforeUnloadEvent: { prototype: BeforeUnloadEvent; new(): BeforeUnloadEvent; -} +}; interface BiquadFilterNode extends AudioNode { - readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; + readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -1501,7 +1501,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -1514,16 +1514,305 @@ interface Blob { declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; +}; + +interface Cache { + add(request: RequestInfo): Promise; + addAll(requests: RequestInfo[]): Promise; + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + keys(request?: RequestInfo, options?: CacheQueryOptions): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + put(request: RequestInfo, response: Response): Promise; } +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +interface CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends Object, CanvasPathMethods { + readonly canvas: HTMLCanvasElement; + fillStyle: string | CanvasGradient | CanvasPattern; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + imageSmoothingEnabled: boolean; + lineCap: string; + lineDashOffset: number; + lineJoin: string; + lineWidth: number; + miterLimit: number; + msFillRule: CanvasFillRule; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + mozImageSmoothingEnabled: boolean; + webkitImageSmoothingEnabled: boolean; + oImageSmoothingEnabled: boolean; + beginPath(): void; + clearRect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: CanvasFillRule): void; + createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + drawFocusIfNeeded(element: Element): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; + fill(fillRule?: CanvasFillRule): void; + fillRect(x: number, y: number, w: number, h: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + getLineDash(): number[]; + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + measureText(text: string): TextMetrics; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + restore(): void; + rotate(angle: number): void; + save(): void; + scale(x: number, y: number): void; + setLineDash(segments: number[]): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(path?: Path2D): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + translate(x: number, y: number): void; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +}; + interface CDATASection extends Text { } declare var CDATASection: { prototype: CDATASection; new(): CDATASection; +}; + +interface ChannelMergerNode extends AudioNode { } +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(): ChannelMergerNode; +}; + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(): ChannelSplitterNode; +}; + +interface CharacterData extends Node, ChildNode { + data: string; + readonly length: number; + appendData(arg: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, arg: string): void; + replaceData(offset: number, count: number, arg: string): void; + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +}; + +interface ClientRect { + bottom: number; + readonly height: number; + left: number; + right: number; + top: number; + readonly width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +}; + +interface ClientRectList { + readonly length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +}; + +interface ClipboardEvent extends Event { + readonly clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +}; + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(): Comment; +}; + +interface CompositionEvent extends UIEvent { + readonly data: string; + readonly locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +}; + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: any, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...data: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer | null; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(): ConvolverNode; +}; + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +}; + +interface Crypto extends Object, RandomSource { + readonly subtle: SubtleCrypto; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +}; + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +}; + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +}; + interface CSS { supports(property: string, value?: string): boolean; } @@ -1536,7 +1825,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -1545,7 +1834,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1556,7 +1845,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -1567,7 +1856,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -1577,7 +1866,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1590,7 +1879,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -1599,7 +1888,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -1609,7 +1898,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -1621,7 +1910,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -1631,8 +1920,8 @@ interface CSSRule { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1648,8 +1937,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1657,7 +1946,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -1668,13 +1957,13 @@ interface CSSRuleList { declare var CSSRuleList: { prototype: CSSRuleList; new(): CSSRuleList; -} +}; interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignSelf: string | null; alignmentBaseline: string | null; + alignSelf: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -1750,9 +2039,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; + columns: string | null; columnSpan: string | null; columnWidth: any; - columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -1822,24 +2111,24 @@ interface CSSStyleDeclaration { minHeight: string | null; minWidth: string | null; msContentZoomChaining: string | null; + msContentZooming: string | null; msContentZoomLimit: string | null; msContentZoomLimitMax: any; msContentZoomLimitMin: any; msContentZoomSnap: string | null; msContentZoomSnapPoints: string | null; msContentZoomSnapType: string | null; - msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumnSpan: any; msGridColumns: string | null; + msGridColumnSpan: any; msGridRow: any; msGridRowAlign: string | null; - msGridRowSpan: any; msGridRows: string | null; + msGridRowSpan: any; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -1975,9 +2264,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; + webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; - webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -2029,7 +2318,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -2040,7 +2329,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -2066,7 +2355,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -2074,296 +2363,7 @@ interface CSSSupportsRule extends CSSConditionRule { declare var CSSSupportsRule: { prototype: CSSSupportsRule; new(): CSSSupportsRule; -} - -interface Cache { - add(request: RequestInfo): Promise; - addAll(requests: RequestInfo[]): Promise; - delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; - put(request: RequestInfo, response: Response): Promise; -} - -declare var Cache: { - prototype: Cache; - new(): Cache; -} - -interface CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; -} - -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -} - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; -} - -declare var CanvasGradient: { - prototype: CanvasGradient; - new(): CanvasGradient; -} - -interface CanvasPattern { - setTransform(matrix: SVGMatrix): void; -} - -declare var CanvasPattern: { - prototype: CanvasPattern; - new(): CanvasPattern; -} - -interface CanvasRenderingContext2D extends Object, CanvasPathMethods { - readonly canvas: HTMLCanvasElement; - fillStyle: string | CanvasGradient | CanvasPattern; - font: string; - globalAlpha: number; - globalCompositeOperation: string; - imageSmoothingEnabled: boolean; - lineCap: string; - lineDashOffset: number; - lineJoin: string; - lineWidth: number; - miterLimit: number; - msFillRule: CanvasFillRule; - shadowBlur: number; - shadowColor: string; - shadowOffsetX: number; - shadowOffsetY: number; - strokeStyle: string | CanvasGradient | CanvasPattern; - textAlign: string; - textBaseline: string; - mozImageSmoothingEnabled: boolean; - webkitImageSmoothingEnabled: boolean; - oImageSmoothingEnabled: boolean; - beginPath(): void; - clearRect(x: number, y: number, w: number, h: number): void; - clip(fillRule?: CanvasFillRule): void; - createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; - createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; - createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; - createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; - drawFocusIfNeeded(element: Element): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; - fill(fillRule?: CanvasFillRule): void; - fillRect(x: number, y: number, w: number, h: number): void; - fillText(text: string, x: number, y: number, maxWidth?: number): void; - getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; - getLineDash(): number[]; - isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; - measureText(text: string): TextMetrics; - putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; - restore(): void; - rotate(angle: number): void; - save(): void; - scale(x: number, y: number): void; - setLineDash(segments: number[]): void; - setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - stroke(path?: Path2D): void; - strokeRect(x: number, y: number, w: number, h: number): void; - strokeText(text: string, x: number, y: number, maxWidth?: number): void; - transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - translate(x: number, y: number): void; -} - -declare var CanvasRenderingContext2D: { - prototype: CanvasRenderingContext2D; - new(): CanvasRenderingContext2D; -} - -interface ChannelMergerNode extends AudioNode { -} - -declare var ChannelMergerNode: { - prototype: ChannelMergerNode; - new(): ChannelMergerNode; -} - -interface ChannelSplitterNode extends AudioNode { -} - -declare var ChannelSplitterNode: { - prototype: ChannelSplitterNode; - new(): ChannelSplitterNode; -} - -interface CharacterData extends Node, ChildNode { - data: string; - readonly length: number; - appendData(arg: string): void; - deleteData(offset: number, count: number): void; - insertData(offset: number, arg: string): void; - replaceData(offset: number, count: number, arg: string): void; - substringData(offset: number, count: number): string; -} - -declare var CharacterData: { - prototype: CharacterData; - new(): CharacterData; -} - -interface ClientRect { - bottom: number; - readonly height: number; - left: number; - right: number; - top: number; - readonly width: number; -} - -declare var ClientRect: { - prototype: ClientRect; - new(): ClientRect; -} - -interface ClientRectList { - readonly length: number; - item(index: number): ClientRect; - [index: number]: ClientRect; -} - -declare var ClientRectList: { - prototype: ClientRectList; - new(): ClientRectList; -} - -interface ClipboardEvent extends Event { - readonly clipboardData: DataTransfer; -} - -declare var ClipboardEvent: { - prototype: ClipboardEvent; - new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; -} - -interface CloseEvent extends Event { - readonly code: number; - readonly reason: string; - readonly wasClean: boolean; - initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; -} - -declare var CloseEvent: { - prototype: CloseEvent; - new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; -} - -interface Comment extends CharacterData { - text: string; -} - -declare var Comment: { - prototype: Comment; - new(): Comment; -} - -interface CompositionEvent extends UIEvent { - readonly data: string; - readonly locale: string; - initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; -} - -declare var CompositionEvent: { - prototype: CompositionEvent; - new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; -} - -interface Console { - assert(test?: boolean, message?: string, ...optionalParams: any[]): void; - clear(): void; - count(countTitle?: string): void; - debug(message?: any, ...optionalParams: any[]): void; - dir(value?: any, ...optionalParams: any[]): void; - dirxml(value: any): void; - error(message?: any, ...optionalParams: any[]): void; - exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; - groupEnd(): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: Element): boolean; - profile(reportName?: string): void; - profileEnd(): void; - select(element: Element): void; - table(...data: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; -} - -declare var Console: { - prototype: Console; - new(): Console; -} - -interface ConvolverNode extends AudioNode { - buffer: AudioBuffer | null; - normalize: boolean; -} - -declare var ConvolverNode: { - prototype: ConvolverNode; - new(): ConvolverNode; -} - -interface Coordinates { - readonly accuracy: number; - readonly altitude: number | null; - readonly altitudeAccuracy: number | null; - readonly heading: number | null; - readonly latitude: number; - readonly longitude: number; - readonly speed: number | null; -} - -declare var Coordinates: { - prototype: Coordinates; - new(): Coordinates; -} - -interface Crypto extends Object, RandomSource { - readonly subtle: SubtleCrypto; -} - -declare var Crypto: { - prototype: Crypto; - new(): Crypto; -} - -interface CryptoKey { - readonly algorithm: KeyAlgorithm; - readonly extractable: boolean; - readonly type: string; - readonly usages: string[]; -} - -declare var CryptoKey: { - prototype: CryptoKey; - new(): CryptoKey; -} - -interface CryptoKeyPair { - privateKey: CryptoKey; - publicKey: CryptoKey; -} - -declare var CryptoKeyPair: { - prototype: CryptoKeyPair; - new(): CryptoKeyPair; -} +}; interface CustomEvent extends Event { readonly detail: any; @@ -2373,150 +2373,7 @@ interface CustomEvent extends Event { declare var CustomEvent: { prototype: CustomEvent; new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; -} - -interface DOMError { - readonly name: string; - toString(): string; -} - -declare var DOMError: { - prototype: DOMError; - new(): DOMError; -} - -interface DOMException { - readonly code: number; - readonly message: string; - readonly name: string; - toString(): string; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -declare var DOMException: { - prototype: DOMException; - new(): DOMException; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -interface DOMImplementation { - createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; - createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; - createHTMLDocument(title: string): Document; - hasFeature(feature: string | null, version: string | null): boolean; -} - -declare var DOMImplementation: { - prototype: DOMImplementation; - new(): DOMImplementation; -} - -interface DOMParser { - parseFromString(source: string, mimeType: string): Document; -} - -declare var DOMParser: { - prototype: DOMParser; - new(): DOMParser; -} - -interface DOMSettableTokenList extends DOMTokenList { - value: string; -} - -declare var DOMSettableTokenList: { - prototype: DOMSettableTokenList; - new(): DOMSettableTokenList; -} - -interface DOMStringList { - readonly length: number; - contains(str: string): boolean; - item(index: number): string | null; - [index: number]: string; -} - -declare var DOMStringList: { - prototype: DOMStringList; - new(): DOMStringList; -} - -interface DOMStringMap { - [name: string]: string | undefined; -} - -declare var DOMStringMap: { - prototype: DOMStringMap; - new(): DOMStringMap; -} - -interface DOMTokenList { - readonly length: number; - add(...token: string[]): void; - contains(token: string): boolean; - item(index: number): string; - remove(...token: string[]): void; - toString(): string; - toggle(token: string, force?: boolean): boolean; - [index: number]: string; -} - -declare var DOMTokenList: { - prototype: DOMTokenList; - new(): DOMTokenList; -} +}; interface DataCue extends TextTrackCue { data: ArrayBuffer; @@ -2527,7 +2384,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -2544,7 +2401,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -2557,7 +2414,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -2571,7 +2428,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -2584,7 +2441,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -2593,7 +2450,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -2604,7 +2461,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -2613,7 +2470,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -2626,7 +2483,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -2639,7 +2496,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -2650,7 +2507,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -2745,299 +2602,291 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { /** - * Sets or gets the URL for the current document. - */ - readonly URL: string; - /** - * Gets the URL for the document, stripped of any character encoding. - */ - readonly URLUnencoded: string; - /** - * Gets the object that has the focus when the parent document has focus. - */ + * Gets the object that has the focus when the parent document has focus. + */ readonly activeElement: Element; /** - * Sets or gets the color of all active links in the document. - */ + * Sets or gets the color of all active links in the document. + */ alinkColor: string; /** - * Returns a reference to the collection of elements contained by the object. - */ + * Returns a reference to the collection of elements contained by the object. + */ readonly all: HTMLAllCollection; /** - * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. - */ + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ anchors: HTMLCollectionOf; /** - * Retrieves a collection of all applet objects in the document. - */ + * Retrieves a collection of all applet objects in the document. + */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. - */ + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ bgColor: string; /** - * Specifies the beginning and end of the document body. - */ + * Specifies the beginning and end of the document body. + */ body: HTMLElement; readonly characterSet: string; /** - * Gets or sets the character set used to encode the object. - */ + * Gets or sets the character set used to encode the object. + */ charset: string; /** - * Gets a value that indicates whether standards-compliant mode is switched on for the object. - */ + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ readonly compatMode: string; cookie: string; readonly currentScript: HTMLScriptElement | SVGScriptElement; readonly defaultView: Window; /** - * Sets or gets a value that indicates whether the document can be edited. - */ + * Sets or gets a value that indicates whether the document can be edited. + */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. - */ + * Sets or retrieves a value that indicates the reading order of the object. + */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. - */ + * Gets an object representing the document type declaration associated with the current document. + */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. - */ + * Gets a reference to the root node of the document. + */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. - */ + * Sets or gets the security domain of the document. + */ domain: string; /** - * Retrieves a collection of all embed objects in the document. - */ + * Retrieves a collection of all embed objects in the document. + */ embeds: HTMLCollectionOf; /** - * Sets or gets the foreground (text) color of the document. - */ + * Sets or gets the foreground (text) color of the document. + */ fgColor: string; /** - * Retrieves a collection, in source order, of all form objects in the document. - */ + * Retrieves a collection, in source order, of all form objects in the document. + */ forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; readonly hidden: boolean; /** - * Retrieves a collection, in source order, of img objects in the document. - */ + * Retrieves a collection, in source order, of img objects in the document. + */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. - */ + * Gets the implementation object of the current document. + */ readonly implementation: DOMImplementation; /** - * Returns the character encoding used to create the webpage that is loaded into the document object. - */ + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. - */ + * Gets the date that the page was last modified, if the page supplies one. + */ readonly lastModified: string; /** - * Sets or gets the color of the document links. - */ + * Sets or gets the color of the document links. + */ linkColor: string; /** - * Retrieves a collection of all a objects that specify the href property and all area objects in the document. - */ + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ links: HTMLCollectionOf; /** - * Contains information about the current URL. - */ + * Contains information about the current URL. + */ readonly location: Location; - msCSSOMElementFloatMetrics: boolean; msCapsLockWarningOff: boolean; + msCSSOMElementFloatMetrics: boolean; /** - * Fires when the user aborts the download. - * @param ev The event. - */ + * Fires when the user aborts the download. + * @param ev The event. + */ onabort: (this: Document, ev: UIEvent) => any; /** - * Fires when the object is set as the active element. - * @param ev The event. - */ + * Fires when the object is set as the active element. + * @param ev The event. + */ onactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the object is set as the active element. - * @param ev The event. - */ + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ onbeforeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the activeElement is changed from the current object to another object in the parent document. - * @param ev The event. - */ + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ onbeforedeactivate: (this: Document, ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. - * @param ev The focus event. - */ + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ onblur: (this: Document, ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. - * @param ev The event. - */ + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ oncanplay: (this: Document, ev: Event) => any; oncanplaythrough: (this: Document, ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. - * @param ev The event. - */ + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ onchange: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the left mouse button on the object - * @param ev The mouse event. - */ + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ onclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. - * @param ev The mouse event. - */ + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ oncontextmenu: (this: Document, ev: PointerEvent) => any; /** - * Fires when the user double-clicks the object. - * @param ev The mouse event. - */ + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ ondblclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the activeElement is changed from the current object to another object in the parent document. - * @param ev The UI Event - */ + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ ondeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires on the source object continuously during a drag operation. - * @param ev The event. - */ + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ ondrag: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user releases the mouse at the close of a drag operation. - * @param ev The event. - */ + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ ondragend: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target element when the user drags the object to a valid drop target. - * @param ev The drag event. - */ + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ ondragenter: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. - * @param ev The drag event. - */ + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ ondragleave: (this: Document, ev: DragEvent) => any; /** - * Fires on the target element continuously while the user drags the object over a valid drop target. - * @param ev The event. - */ + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ ondragover: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. - * @param ev The event. - */ + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ ondragstart: (this: Document, ev: DragEvent) => any; ondrop: (this: Document, ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. - * @param ev The event. - */ + * Occurs when the duration attribute is updated. + * @param ev The event. + */ ondurationchange: (this: Document, ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. - * @param ev The event. - */ + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ onemptied: (this: Document, ev: Event) => any; /** - * Occurs when the end of playback is reached. - * @param ev The event - */ + * Occurs when the end of playback is reached. + * @param ev The event + */ onended: (this: Document, ev: MediaStreamErrorEvent) => any; /** - * Fires when an error occurs during object loading. - * @param ev The event. - */ + * Fires when an error occurs during object loading. + * @param ev The event. + */ onerror: (this: Document, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - * @param ev The event. - */ + * Fires when the object receives focus. + * @param ev The event. + */ onfocus: (this: Document, ev: FocusEvent) => any; onfullscreenchange: (this: Document, ev: Event) => any; onfullscreenerror: (this: Document, ev: Event) => any; oninput: (this: Document, ev: Event) => any; oninvalid: (this: Document, ev: Event) => any; /** - * Fires when the user presses a key. - * @param ev The keyboard event - */ + * Fires when the user presses a key. + * @param ev The keyboard event + */ onkeydown: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user presses an alphanumeric key. - * @param ev The event. - */ + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ onkeypress: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user releases a key. - * @param ev The keyboard event - */ + * Fires when the user releases a key. + * @param ev The keyboard event + */ onkeyup: (this: Document, ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. - * @param ev The event. - */ + * Fires immediately after the browser loads the object. + * @param ev The event. + */ onload: (this: Document, ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. - * @param ev The event. - */ + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ onloadeddata: (this: Document, ev: Event) => any; /** - * Occurs when the duration and dimensions of the media have been determined. - * @param ev The event. - */ + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ onloadedmetadata: (this: Document, ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. - * @param ev The event. - */ + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ onloadstart: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. - * @param ev The mouse event. - */ + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ onmousedown: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ onmousemove: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ onmouseout: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer into the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ onmouseover: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. - * @param ev The mouse event. - */ + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ onmouseup: (this: Document, ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. - * @param ev The mouse event - */ + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ onmousewheel: (this: Document, ev: WheelEvent) => any; onmscontentzoom: (this: Document, ev: UIEvent) => any; onmsgesturechange: (this: Document, ev: MSGestureEvent) => any; @@ -3057,146 +2906,154 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (this: Document, ev: MSPointerEvent) => any; onmspointerup: (this: Document, ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ onmssitemodejumplistitemremoved: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ onmsthumbnailclick: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when playback is paused. - * @param ev The event. - */ + * Occurs when playback is paused. + * @param ev The event. + */ onpause: (this: Document, ev: Event) => any; /** - * Occurs when the play method is requested. - * @param ev The event. - */ + * Occurs when the play method is requested. + * @param ev The event. + */ onplay: (this: Document, ev: Event) => any; /** - * Occurs when the audio or video has started playing. - * @param ev The event. - */ + * Occurs when the audio or video has started playing. + * @param ev The event. + */ onplaying: (this: Document, ev: Event) => any; onpointerlockchange: (this: Document, ev: Event) => any; onpointerlockerror: (this: Document, ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. - * @param ev The event. - */ + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ onprogress: (this: Document, ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. - * @param ev The event. - */ + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ onratechange: (this: Document, ev: Event) => any; /** - * Fires when the state of the object has changed. - * @param ev The event - */ + * Fires when the state of the object has changed. + * @param ev The event + */ onreadystatechange: (this: Document, ev: Event) => any; /** - * Fires when the user resets a form. - * @param ev The event. - */ + * Fires when the user resets a form. + * @param ev The event. + */ onreset: (this: Document, ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. - * @param ev The event. - */ + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ onscroll: (this: Document, ev: UIEvent) => any; /** - * Occurs when the seek operation ends. - * @param ev The event. - */ + * Occurs when the seek operation ends. + * @param ev The event. + */ onseeked: (this: Document, ev: Event) => any; /** - * Occurs when the current playback position is moved. - * @param ev The event. - */ + * Occurs when the current playback position is moved. + * @param ev The event. + */ onseeking: (this: Document, ev: Event) => any; /** - * Fires when the current selection changes. - * @param ev The event. - */ + * Fires when the current selection changes. + * @param ev The event. + */ onselect: (this: Document, ev: UIEvent) => any; /** - * Fires when the selection state of a document changes. - * @param ev The event. - */ + * Fires when the selection state of a document changes. + * @param ev The event. + */ onselectionchange: (this: Document, ev: Event) => any; onselectstart: (this: Document, ev: Event) => any; /** - * Occurs when the download has stopped. - * @param ev The event. - */ + * Occurs when the download has stopped. + * @param ev The event. + */ onstalled: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the Stop button or leaves the Web page. - * @param ev The event. - */ + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ onstop: (this: Document, ev: Event) => any; onsubmit: (this: Document, ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. - * @param ev The event. - */ + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ onsuspend: (this: Document, ev: Event) => any; /** - * Occurs to indicate the current playback position. - * @param ev The event. - */ + * Occurs to indicate the current playback position. + * @param ev The event. + */ ontimeupdate: (this: Document, ev: Event) => any; ontouchcancel: (ev: TouchEvent) => any; ontouchend: (ev: TouchEvent) => any; ontouchmove: (ev: TouchEvent) => any; ontouchstart: (ev: TouchEvent) => any; /** - * Occurs when the volume is changed, or playback is muted or unmuted. - * @param ev The event. - */ + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ onvolumechange: (this: Document, ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. - * @param ev The event. - */ + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ onwaiting: (this: Document, ev: Event) => any; onwebkitfullscreenchange: (this: Document, ev: Event) => any; onwebkitfullscreenerror: (this: Document, ev: Event) => any; plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** - * Retrieves a value that indicates the current state of the object. - */ + * Retrieves a value that indicates the current state of the object. + */ readonly readyState: string; /** - * Gets the URL of the location that referred the user to the current page. - */ + * Gets the URL of the location that referred the user to the current page. + */ readonly referrer: string; /** - * Gets the root svg element in the document hierarchy. - */ + * Gets the root svg element in the document hierarchy. + */ readonly rootElement: SVGSVGElement; /** - * Retrieves a collection of all script objects in the document. - */ + * Retrieves a collection of all script objects in the document. + */ scripts: HTMLCollectionOf; readonly scrollingElement: Element | null; /** - * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. - */ + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ readonly styleSheets: StyleSheetList; /** - * Contains the title of the document. - */ + * Contains the title of the document. + */ title: string; + /** + * Sets or gets the URL for the current document. + */ + readonly URL: string; + /** + * Gets the URL for the document, stripped of any character encoding. + */ + readonly URLUnencoded: string; readonly visibilityState: VisibilityState; - /** - * Sets or gets the color of the links that the user has visited. - */ + /** + * Sets or gets the color of the links that the user has visited. + */ vlinkColor: string; readonly webkitCurrentFullScreenElement: Element | null; readonly webkitFullscreenElement: Element | null; @@ -3205,243 +3062,243 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven readonly xmlEncoding: string | null; xmlStandalone: boolean; /** - * Gets or sets the version attribute specified in the declaration of an XML document. - */ + * Gets or sets the version attribute specified in the declaration of an XML document. + */ xmlVersion: string | null; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; clear(): void; /** - * Closes an output stream and forces the sent data to display. - */ + * Closes an output stream and forces the sent data to display. + */ close(): void; /** - * Creates an attribute object with a specified name. - * @param name String that sets the attribute object's name. - */ + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ createAttribute(name: string): Attr; createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; createCDATASection(data: string): CDATASection; /** - * Creates a comment object with the specified data. - * @param data Sets the comment object's data. - */ + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ createComment(data: string): Comment; /** - * Creates a new document. - */ + * Creates a new document. + */ createDocumentFragment(): DocumentFragment; /** - * Creates an instance of the element for the specified tag. - * @param tagName The name of an element. - */ + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ createElement(tagName: K): HTMLElementTagNameMap[K]; createElement(tagName: string): HTMLElement; - createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; - createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list - * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; + createNSResolver(nodeResolver: Node): XPathNSResolver; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. - */ + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + */ createRange(): Range; /** - * Creates a text string from the specified value. - * @param data String that specifies the nodeValue property of the text node. - */ + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ createTextNode(data: string): Text; createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; createTouchList(...touches: Touch[]): TouchList; /** - * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. - * @param filter A custom NodeFilter function to use. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. - * @param x The x-offset - * @param y The y-offset - */ + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ elementFromPoint(x: number, y: number): Element; evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; /** - * Executes a command on the current document, current selection, or the given range. - * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. - * @param showUI Display the user interface, defaults to false. - * @param value Value to assign. - */ + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ execCommand(commandId: string, showUI?: boolean, value?: any): boolean; /** - * Displays help information for the given command identifier. - * @param commandId Displays help information for the given command identifier. - */ + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ execCommandShowHelp(commandId: string): boolean; exitFullscreen(): void; exitPointerLock(): void; /** - * Causes the element to receive the focus and executes the code specified by the onfocus event. - */ + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ focus(): void; /** - * Returns a reference to the first object with the specified value of the ID or NAME attribute. - * @param elementId String that specifies the ID value. Case-insensitive. - */ + * Returns a reference to the first object with the specified value of the ID or NAME attribute. + * @param elementId String that specifies the ID value. Case-insensitive. + */ getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** - * Gets a collection of objects based on the value of the NAME or ID attribute. - * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. - */ + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ getElementsByName(elementName: string): NodeListOf; /** - * Retrieves a collection of objects based on the specified element name. - * @param name Specifies the name of an element. - */ + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ getElementsByTagName(tagname: K): ElementListTagNameMap[K]; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; /** - * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. - */ + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ getSelection(): Selection; /** - * Gets a value indicating whether the object currently has focus. - */ + * Gets a value indicating whether the object currently has focus. + */ hasFocus(): boolean; importNode(importedNode: T, deep: boolean): T; msElementsFromPoint(x: number, y: number): NodeListOf; msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; /** - * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. - * @param url Specifies a MIME type for the document. - * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. - * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. - * @param replace Specifies whether the existing entry for the document is replaced in the history list. - */ + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** - * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. - * @param commandId Specifies a command identifier. - */ + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + */ queryCommandEnabled(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ queryCommandIndeterm(commandId: string): boolean; /** - * Returns a Boolean value that indicates the current state of the command. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ queryCommandState(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the current command is supported on the current range. - * @param commandId Specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ queryCommandSupported(commandId: string): boolean; /** - * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. - */ + * Retrieves the string associated with a command. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + */ queryCommandText(commandId: string): string; /** - * Returns the current value of the document, range, or current selection for the given command. - * @param commandId String that specifies a command identifier. - */ + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ queryCommandValue(commandId: string): string; releaseEvents(): void; /** - * Allows updating the print settings for the page. - */ + * Allows updating the print settings for the page. + */ updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. - * @param content Specifies the text and HTML tags to write. - */ + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. - * @param content The text and HTML tags to write. - */ + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + */ writeln(...content: string[]): void; addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3450,7 +3307,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven declare var Document: { prototype: Document; new(): Document; -} +}; interface DocumentFragment extends Node, NodeSelector, ParentNode { getElementById(elementId: string): HTMLElement | null; @@ -3459,7 +3316,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -3473,8 +3330,151 @@ interface DocumentType extends Node, ChildNode { declare var DocumentType: { prototype: DocumentType; new(): DocumentType; +}; + +interface DOMError { + readonly name: string; + toString(): string; } +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +}; + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + toString(): string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +}; + +interface DOMImplementation { + createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createHTMLDocument(title: string): Document; + hasFeature(feature: string | null, version: string | null): boolean; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +}; + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +}; + +interface DOMStringList { + readonly length: number; + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +}; + +interface DOMStringMap { + [name: string]: string | undefined; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +}; + +interface DOMTokenList { + readonly length: number; + add(...token: string[]): void; + contains(token: string): boolean; + item(index: number): string; + remove(...token: string[]): void; + toggle(token: string, force?: boolean): boolean; + toString(): string; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DragEvent extends MouseEvent { readonly dataTransfer: DataTransfer; initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; @@ -3484,7 +3484,7 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; new(): DragEvent; -} +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -3498,27 +3498,7 @@ interface DynamicsCompressorNode extends AudioNode { declare var DynamicsCompressorNode: { prototype: DynamicsCompressorNode; new(): DynamicsCompressorNode; -} - -interface EXT_frag_depth { -} - -declare var EXT_frag_depth: { - prototype: EXT_frag_depth; - new(): EXT_frag_depth; -} - -interface EXT_texture_filter_anisotropic { - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} +}; interface ElementEventMap extends GlobalEventHandlersEventMap { "ariarequest": Event; @@ -3599,9 +3579,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; getElementsByTagName(name: K): ElementListTagNameMap[K]; @@ -3619,18 +3599,18 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec msZoomTo(args: MsZoomToOptions): void; releasePointerCapture(pointerId: number): void; removeAttribute(qualifiedName: string): void; - removeAttributeNS(namespaceURI: string, localName: string): void; removeAttributeNode(oldAttr: Attr): Attr; + removeAttributeNS(namespaceURI: string, localName: string): void; requestFullscreen(): void; requestPointerLock(): void; setAttribute(name: string, value: string): void; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setPointerCapture(pointerId: number): void; webkitMatchesSelector(selectors: string): boolean; - webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; + webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; closest(selector: string): Element | null; @@ -3641,9 +3621,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec scrollTo(x: number, y: number): void; scrollBy(options?: ScrollToOptions): void; scrollBy(x: number, y: number): void; - insertAdjacentElement(position: string, insertedElement: Element): Element | null; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3652,7 +3632,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -3666,12 +3646,12 @@ interface ErrorEvent extends Event { declare var ErrorEvent: { prototype: ErrorEvent; new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent; -} +}; interface Event { readonly bubbles: boolean; - cancelBubble: boolean; readonly cancelable: boolean; + cancelBubble: boolean; readonly currentTarget: EventTarget; readonly defaultPrevented: boolean; readonly eventPhase: number; @@ -3698,7 +3678,7 @@ declare var Event: { readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; -} +}; interface EventTarget { addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -3709,8 +3689,28 @@ interface EventTarget { declare var EventTarget: { prototype: EventTarget; new(): EventTarget; +}; + +interface EXT_frag_depth { } +declare var EXT_frag_depth: { + prototype: EXT_frag_depth; + new(): EXT_frag_depth; +}; + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +declare var EXT_texture_filter_anisotropic: { + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; @@ -3724,7 +3724,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -3732,7 +3732,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -3743,7 +3743,7 @@ interface File extends Blob { declare var File: { prototype: File; new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} +}; interface FileList { readonly length: number; @@ -3754,7 +3754,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -3769,7 +3769,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -3779,7 +3779,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -3793,7 +3793,7 @@ interface FocusNavigationEvent extends Event { declare var FocusNavigationEvent: { prototype: FocusNavigationEvent; new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent; -} +}; interface FormData { append(name: string, value: string | Blob, fileName?: string): void; @@ -3807,7 +3807,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -3816,7 +3816,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -3831,7 +3831,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -3841,7 +3841,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -3850,7 +3850,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -3861,8 +3861,48 @@ interface Geolocation { declare var Geolocation: { prototype: Geolocation; new(): Geolocation; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string | null; + readonly oldURL: string | null; } +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: ForEachCallback): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; +} + +declare var Headers: { + prototype: Headers; + new(init?: any): Headers; +}; + +interface History { + readonly length: number; + readonly state: any; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; +} + +declare var History: { + prototype: History; + new(): History; +}; + interface HTMLAllCollection { readonly length: number; item(nameOrIndex?: string): HTMLCollection | Element | null; @@ -3873,87 +3913,87 @@ interface HTMLAllCollection { declare var HTMLAllCollection: { prototype: HTMLAllCollection; new(): HTMLAllCollection; -} +}; interface HTMLAnchorElement extends HTMLElement { - Methods: string; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Contains the anchor portion of the URL including the hash sign (#). - */ + * Contains the anchor portion of the URL including the hash sign (#). + */ hash: string; /** - * Contains the hostname and port values of the URL. - */ + * Contains the hostname and port values of the URL. + */ host: string; /** - * Contains the hostname of a URL. - */ + * Contains the hostname of a URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; + Methods: string; readonly mimeType: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; readonly nameProp: string; /** - * Contains the pathname of the URL. - */ + * Contains the pathname of the URL. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Contains the protocol of the URL. - */ + * Contains the protocol of the URL. + */ protocol: string; readonly protocolLong: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; type: string; urn: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3962,70 +4002,70 @@ interface HTMLAnchorElement extends HTMLElement { declare var HTMLAnchorElement: { prototype: HTMLAnchorElement; new(): HTMLAnchorElement; -} +}; interface HTMLAppletElement extends HTMLElement { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ altHtml: string; /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; border: string; code: string; /** - * Sets or retrieves the URL of the component. - */ + * Sets or retrieves the URL of the component. + */ codeBase: string; /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ + * Sets or retrieves the Internet media type for the code associated with the object. + */ codeType: string; /** - * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. - */ + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ readonly contentDocument: Document; /** - * Sets or retrieves the URL that references the data of the object. - */ + * Sets or retrieves the URL that references the data of the object. + */ data: string; /** - * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ declare: boolean; readonly form: HTMLFormElement; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hspace: number; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; object: string | null; /** - * Sets or retrieves a message to be displayed while an object is loading. - */ + * Sets or retrieves a message to be displayed while an object is loading. + */ standby: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; vspace: number; width: number; @@ -4036,66 +4076,66 @@ interface HTMLAppletElement extends HTMLElement { declare var HTMLAppletElement: { prototype: HTMLAppletElement; new(): HTMLAppletElement; -} +}; interface HTMLAreaElement extends HTMLElement { /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Sets or retrieves the subsection of the href property that follows the number sign (#). - */ + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ hash: string; /** - * Sets or retrieves the hostname and port number of the location or URL. - */ + * Sets or retrieves the hostname and port number of the location or URL. + */ host: string; /** - * Sets or retrieves the host name part of the location or URL. - */ + * Sets or retrieves the host name part of the location or URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or gets whether clicks in this region cause action. - */ + * Sets or gets whether clicks in this region cause action. + */ noHref: boolean; /** - * Sets or retrieves the file name or path specified by the object. - */ + * Sets or retrieves the file name or path specified by the object. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Sets or retrieves the protocol portion of a URL. - */ + * Sets or retrieves the protocol portion of a URL. + */ protocol: string; rel: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4104,7 +4144,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -4112,7 +4152,7 @@ interface HTMLAreasCollection extends HTMLCollectionBase { declare var HTMLAreasCollection: { prototype: HTMLAreasCollection; new(): HTMLAreasCollection; -} +}; interface HTMLAudioElement extends HTMLMediaElement { addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; @@ -4122,30 +4162,16 @@ interface HTMLAudioElement extends HTMLMediaElement { declare var HTMLAudioElement: { prototype: HTMLAudioElement; new(): HTMLAudioElement; -} - -interface HTMLBRElement extends HTMLElement { - /** - * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. - */ - clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBRElement: { - prototype: HTMLBRElement; - new(): HTMLBRElement; -} +}; interface HTMLBaseElement extends HTMLElement { /** - * Gets or sets the baseline URL on which relative links are based. - */ + * Gets or sets the baseline URL on which relative links are based. + */ href: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4154,16 +4180,16 @@ interface HTMLBaseElement extends HTMLElement { declare var HTMLBaseElement: { prototype: HTMLBaseElement; new(): HTMLBaseElement; -} +}; interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; /** - * Sets or retrieves the font size of the object. - */ + * Sets or retrieves the font size of the object. + */ size: number; addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4172,7 +4198,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4231,71 +4257,85 @@ interface HTMLBodyElement extends HTMLElement { declare var HTMLBodyElement: { prototype: HTMLBodyElement; new(): HTMLBodyElement; +}; + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +}; + interface HTMLButtonElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; - /** - * Sets or retrieves the name of the object. - */ + /** + * Sets or retrieves the name of the object. + */ name: string; status: any; /** - * Gets the classification and default behavior of the button. - */ + * Gets the classification and default behavior of the button. + */ type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; - /** - * Sets or retrieves the default or selected value of the control. - */ + /** + * Sets or retrieves the default or selected value of the control. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4304,32 +4344,32 @@ interface HTMLButtonElement extends HTMLElement { declare var HTMLButtonElement: { prototype: HTMLButtonElement; new(): HTMLButtonElement; -} +}; interface HTMLCanvasElement extends HTMLElement { /** - * Gets or sets the height of a canvas element on a document. - */ + * Gets or sets the height of a canvas element on a document. + */ height: number; /** - * Gets or sets the width of a canvas element on a document. - */ + * Gets or sets the width of a canvas element on a document. + */ width: number; /** - * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. - * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); - */ + * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. + * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); + */ getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** - * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. - */ + * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. + */ msToBlob(): Blob; /** - * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. - * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. - */ + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. + */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -4339,42 +4379,31 @@ interface HTMLCanvasElement extends HTMLElement { declare var HTMLCanvasElement: { prototype: HTMLCanvasElement; new(): HTMLCanvasElement; -} +}; interface HTMLCollectionBase { /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Retrieves an object from various collections. - */ + * Retrieves an object from various collections. + */ item(index: number): Element; [index: number]: Element; } interface HTMLCollection extends HTMLCollectionBase { /** - * Retrieves a select object or an object from an options collection. - */ + * Retrieves a select object or an object from an options collection. + */ namedItem(name: string): Element | null; } declare var HTMLCollection: { prototype: HTMLCollection; new(): HTMLCollection; -} - -interface HTMLDListElement extends HTMLElement { - compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLDListElement: { - prototype: HTMLDListElement; - new(): HTMLDListElement; -} +}; interface HTMLDataElement extends HTMLElement { value: string; @@ -4385,7 +4414,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -4396,7 +4425,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -4407,16 +4436,16 @@ interface HTMLDirectoryElement extends HTMLElement { declare var HTMLDirectoryElement: { prototype: HTMLDirectoryElement; new(): HTMLDirectoryElement; -} +}; interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4425,8 +4454,19 @@ interface HTMLDivElement extends HTMLElement { declare var HTMLDivElement: { prototype: HTMLDivElement; new(): HTMLDivElement; +}; + +interface HTMLDListElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +}; + interface HTMLDocument extends Document { addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4435,7 +4475,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -4608,54 +4648,54 @@ interface HTMLElement extends Element { declare var HTMLElement: { prototype: HTMLElement; new(): HTMLElement; -} +}; interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hidden: any; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Retrieves the palette used for the embedded document. - */ + * Retrieves the palette used for the embedded document. + */ readonly palette: string; /** - * Retrieves the URL of the plug-in used to view an embedded document. - */ + * Retrieves the URL of the plug-in used to view an embedded document. + */ readonly pluginspage: string; readonly readyState: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the height and width units of the embed object. - */ + * Sets or retrieves the height and width units of the embed object. + */ units: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4664,39 +4704,39 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { declare var HTMLEmbedElement: { prototype: HTMLEmbedElement; new(): HTMLEmbedElement; -} +}; interface HTMLFieldSetElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; name: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4705,12 +4745,12 @@ interface HTMLFieldSetElement extends HTMLElement { declare var HTMLFieldSetElement: { prototype: HTMLFieldSetElement; new(): HTMLFieldSetElement; -} +}; interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4719,7 +4759,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -4728,74 +4768,74 @@ interface HTMLFormControlsCollection extends HTMLCollectionBase { declare var HTMLFormControlsCollection: { prototype: HTMLFormControlsCollection; new(): HTMLFormControlsCollection; -} +}; interface HTMLFormElement extends HTMLElement { /** - * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. - */ + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ acceptCharset: string; /** - * Sets or retrieves the URL to which the form content is sent for processing. - */ + * Sets or retrieves the URL to which the form content is sent for processing. + */ action: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Retrieves a collection, in source order, of all controls in a given form. - */ + * Retrieves a collection, in source order, of all controls in a given form. + */ readonly elements: HTMLFormControlsCollection; /** - * Sets or retrieves the MIME encoding for the form. - */ + * Sets or retrieves the MIME encoding for the form. + */ encoding: string; /** - * Sets or retrieves the encoding type for the form. - */ + * Sets or retrieves the encoding type for the form. + */ enctype: string; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Sets or retrieves how to send the form data to the server. - */ + * Sets or retrieves how to send the form data to the server. + */ method: string; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Designates a form that is not validated when submitted. - */ + * Designates a form that is not validated when submitted. + */ noValidate: boolean; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a form object or an object from an elements collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a form object or an object from an elements collection. - */ + * Retrieves a form object or an object from an elements collection. + */ namedItem(name: string): any; /** - * Fires when the user resets a form. - */ + * Fires when the user resets a form. + */ reset(): void; /** - * Fires when a FORM is about to be submitted. - */ + * Fires when a FORM is about to be submitted. + */ submit(): void; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4805,7 +4845,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -4813,68 +4853,68 @@ interface HTMLFrameElementEventMap extends HTMLElementEventMap { interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string | number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLFrameElement, ev: Event) => any; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string | number; addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4883,7 +4923,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4910,33 +4950,33 @@ interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { interface HTMLFrameSetElement extends HTMLElement { border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Sets or retrieves the frame widths of the object. - */ + * Sets or retrieves the frame widths of the object. + */ cols: string; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; name: string; onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; /** - * Fires when the object loses the input focus. - */ + * Fires when the object loses the input focus. + */ onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - */ + * Fires when the object receives focus. + */ onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; onload: (this: HTMLFrameSetElement, ev: Event) => any; @@ -4952,8 +4992,8 @@ interface HTMLFrameSetElement extends HTMLElement { onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** - * Sets or retrieves the frame heights of the object. - */ + * Sets or retrieves the frame heights of the object. + */ rows: string; addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4962,29 +5002,7 @@ interface HTMLFrameSetElement extends HTMLElement { declare var HTMLFrameSetElement: { prototype: HTMLFrameSetElement; new(): HTMLFrameSetElement; -} - -interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. - */ - noShade: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLHRElement: { - prototype: HTMLHRElement; - new(): HTMLHRElement; -} +}; interface HTMLHeadElement extends HTMLElement { profile: string; @@ -4995,12 +5013,12 @@ interface HTMLHeadElement extends HTMLElement { declare var HTMLHeadElement: { prototype: HTMLHeadElement; new(): HTMLHeadElement; -} +}; interface HTMLHeadingElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5009,12 +5027,34 @@ interface HTMLHeadingElement extends HTMLElement { declare var HTMLHeadingElement: { prototype: HTMLHeadingElement; new(): HTMLHeadingElement; +}; + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +}; + interface HTMLHtmlElement extends HTMLElement { /** - * Sets or retrieves the DTD version that governs the current document. - */ + * Sets or retrieves the DTD version that governs the current document. + */ version: string; addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5023,7 +5063,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -5031,79 +5071,79 @@ interface HTMLIFrameElementEventMap extends HTMLElementEventMap { interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; allowFullscreen: boolean; allowPaymentRequest: boolean; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the horizontal margin for the object. - */ + * Sets or retrieves the horizontal margin for the object. + */ hspace: number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5112,86 +5152,86 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLIFrameElement: { prototype: HTMLIFrameElement; new(): HTMLIFrameElement; -} +}; interface HTMLImageElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: number; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; /** - * Sets or retrieves whether the image is a server-side image map. - */ + * Sets or retrieves whether the image is a server-side image map. + */ isMap: boolean; /** - * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. - */ + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ longDesc: string; lowsrc: string; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * The original height of the image resource before sizing. - */ + * The original height of the image resource before sizing. + */ readonly naturalHeight: number; /** - * The original width of the image resource before sizing. - */ + * The original width of the image resource before sizing. + */ readonly naturalWidth: number; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: number; readonly x: number; readonly y: number; @@ -5203,210 +5243,210 @@ interface HTMLImageElement extends HTMLElement { declare var HTMLImageElement: { prototype: HTMLImageElement; new(): HTMLImageElement; -} +}; interface HTMLInputElement extends HTMLElement { /** - * Sets or retrieves a comma-separated list of content types. - */ + * Sets or retrieves a comma-separated list of content types. + */ accept: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ checked: boolean; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ defaultChecked: boolean; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Returns a FileList object on a file type input object. - */ + * Returns a FileList object on a file type input object. + */ readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; indeterminate: boolean; /** - * Specifies the ID of a pre-defined datalist of options for an input element. - */ + * Specifies the ID of a pre-defined datalist of options for an input element. + */ readonly list: HTMLElement; /** - * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. - */ + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ max: string; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. - */ + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ min: string; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a string containing a regular expression that the user's input must match. - */ + * Gets or sets a string containing a regular expression that the user's input must match. + */ pattern: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; selectionDirection: string; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; size: number; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; status: boolean; /** - * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. - */ + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ step: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns the value of the data at the cursor's current position. - */ + * Returns the value of the data at the cursor's current position. + */ value: string; valueAsDate: Date; /** - * Returns the input field value as a number. - */ + * Returns the input field value as a number. + */ valueAsNumber: number; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; webkitdirectory: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Makes the selection equal to the current object. - */ + * Makes the selection equal to the current object. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start?: number, end?: number, direction?: string): void; /** - * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. - * @param n Value to decrement the value by. - */ + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ stepDown(n?: number): void; /** - * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. - * @param n Value to increment the value by. - */ + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ stepUp(n?: number): void; addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5415,31 +5455,16 @@ interface HTMLInputElement extends HTMLElement { declare var HTMLInputElement: { prototype: HTMLInputElement; new(): HTMLInputElement; -} - -interface HTMLLIElement extends HTMLElement { - type: string; - /** - * Sets or retrieves the value of a list item. - */ - value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLLIElement: { - prototype: HTMLLIElement; - new(): HTMLLIElement; -} +}; interface HTMLLabelElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the object to which the given label object is assigned. - */ + * Sets or retrieves the object to which the given label object is assigned. + */ htmlFor: string; addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5448,16 +5473,16 @@ interface HTMLLabelElement extends HTMLElement { declare var HTMLLabelElement: { prototype: HTMLLabelElement; new(): HTMLLabelElement; -} +}; interface HTMLLegendElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ align: string; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5466,41 +5491,56 @@ interface HTMLLegendElement extends HTMLElement { declare var HTMLLegendElement: { prototype: HTMLLegendElement; new(): HTMLLegendElement; +}; + +interface HTMLLIElement extends HTMLElement { + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +}; + interface HTMLLinkElement extends HTMLElement, LinkStyle { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; disabled: boolean; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Sets or retrieves the MIME type of the object. - */ + * Sets or retrieves the MIME type of the object. + */ type: string; import?: Document; integrity: string; @@ -5511,16 +5551,16 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { declare var HTMLLinkElement: { prototype: HTMLLinkElement; new(): HTMLLinkElement; -} +}; interface HTMLMapElement extends HTMLElement { /** - * Retrieves a collection of the area objects defined for the given map object. - */ + * Retrieves a collection of the area objects defined for the given map object. + */ readonly areas: HTMLAreasCollection; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5529,7 +5569,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -5561,7 +5601,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -5570,162 +5610,162 @@ interface HTMLMediaElementEventMap extends HTMLElementEventMap { interface HTMLMediaElement extends HTMLElement { /** - * Returns an AudioTrackList object with the audio tracks for a given video element. - */ + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ readonly audioTracks: AudioTrackList; /** - * Gets or sets a value that indicates whether to start playing the media automatically. - */ + * Gets or sets a value that indicates whether to start playing the media automatically. + */ autoplay: boolean; /** - * Gets a collection of buffered time ranges. - */ + * Gets a collection of buffered time ranges. + */ readonly buffered: TimeRanges; /** - * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). - */ + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ controls: boolean; crossOrigin: string | null; /** - * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. - */ + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ readonly currentSrc: string; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ currentTime: number; defaultMuted: boolean; /** - * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. - */ + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ defaultPlaybackRate: number; /** - * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. - */ + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ readonly duration: number; /** - * Gets information about whether the playback has ended or not. - */ + * Gets information about whether the playback has ended or not. + */ readonly ended: boolean; /** - * Returns an object representing the current error state of the audio or video element. - */ + * Returns an object representing the current error state of the audio or video element. + */ readonly error: MediaError; /** - * Gets or sets a flag to specify whether playback should restart after it completes. - */ + * Gets or sets a flag to specify whether playback should restart after it completes. + */ loop: boolean; readonly mediaKeys: MediaKeys | null; /** - * Specifies the purpose of the audio or video media, such as background audio or alerts. - */ + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ msAudioCategory: string; /** - * Specifies the output device id that the audio will be sent to. - */ + * Specifies the output device id that the audio will be sent to. + */ msAudioDeviceType: string; readonly msGraphicsTrustStatus: MSGraphicsTrust; /** - * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. - */ + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ readonly msKeys: MSMediaKeys; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Specifies whether or not to enable low-latency playback on the media element. - */ + * Specifies whether or not to enable low-latency playback on the media element. + */ msRealTime: boolean; /** - * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. - */ + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ muted: boolean; /** - * Gets the current network activity for the element. - */ + * Gets the current network activity for the element. + */ readonly networkState: number; onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; /** - * Gets a flag that specifies whether playback is paused. - */ + * Gets a flag that specifies whether playback is paused. + */ readonly paused: boolean; /** - * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. - */ + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ playbackRate: number; /** - * Gets TimeRanges for the current media resource that has been played. - */ + * Gets TimeRanges for the current media resource that has been played. + */ readonly played: TimeRanges; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ preload: string; readyState: number; /** - * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. - */ + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ readonly seekable: TimeRanges; /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. - */ + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ readonly seeking: boolean; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcObject: MediaStream | null; readonly textTracks: TextTrackList; readonly videoTracks: VideoTrackList; /** - * Gets or sets the volume level for audio portions of the media element. - */ + * Gets or sets the volume level for audio portions of the media element. + */ volume: number; addTextTrack(kind: string, label?: string, language?: string): TextTrack; /** - * Returns a string that specifies whether the client can play a given media resource type. - */ + * Returns a string that specifies whether the client can play a given media resource type. + */ canPlayType(type: string): string; /** - * Resets the audio or video object and loads a new media resource. - */ + * Resets the audio or video object and loads a new media resource. + */ load(): void; /** - * Clears all effects from the media pipeline. - */ + * Clears all effects from the media pipeline. + */ msClearEffects(): void; msGetAsCastingSource(): any; /** - * Inserts the specified audio effect into media pipeline. - */ + * Inserts the specified audio effect into media pipeline. + */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** - * Specifies the media protection manager for a given media pipeline. - */ + * Specifies the media protection manager for a given media pipeline. + */ msSetMediaProtectionManager(mediaProtectionManager?: any): void; /** - * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. - */ + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ pause(): void; /** - * Loads and starts playback of a media resource. - */ - play(): void; + * Loads and starts playback of a media resource. + */ + play(): Promise; setMediaKeys(mediaKeys: MediaKeys | null): Promise; readonly HAVE_CURRENT_DATA: number; readonly HAVE_ENOUGH_DATA: number; @@ -5752,7 +5792,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -5764,32 +5804,32 @@ interface HTMLMenuElement extends HTMLElement { declare var HTMLMenuElement: { prototype: HTMLMenuElement; new(): HTMLMenuElement; -} +}; interface HTMLMetaElement extends HTMLElement { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Gets or sets meta-information to associate with httpEquiv or name. - */ + * Gets or sets meta-information to associate with httpEquiv or name. + */ content: string; /** - * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. - */ + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ httpEquiv: string; /** - * Sets or retrieves the value specified in the content attribute of the meta object. - */ + * Sets or retrieves the value specified in the content attribute of the meta object. + */ name: string; /** - * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. - */ + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. - */ + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ url: string; addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5798,7 +5838,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -5814,16 +5854,16 @@ interface HTMLMeterElement extends HTMLElement { declare var HTMLMeterElement: { prototype: HTMLMeterElement; new(): HTMLMeterElement; -} +}; interface HTMLModElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; /** - * Sets or retrieves the date and time of a modification to the object. - */ + * Sets or retrieves the date and time of a modification to the object. + */ dateTime: string; addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5832,13 +5872,130 @@ interface HTMLModElement extends HTMLElement { declare var HTMLModElement: { prototype: HTMLModElement; new(): HTMLModElement; +}; + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +}; + interface HTMLOListElement extends HTMLElement { compact: boolean; /** - * The starting number. - */ + * The starting number. + */ start: number; type: string; addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -5848,154 +6005,37 @@ interface HTMLOListElement extends HTMLElement { declare var HTMLOListElement: { prototype: HTMLOListElement; new(): HTMLOListElement; -} - -interface HTMLObjectElement extends HTMLElement, GetSVGDocument { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - /** - * Sets or retrieves the URL of the file containing the compiled Java class. - */ - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - declare: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - readonly readyState: number; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLObjectElement: { - prototype: HTMLObjectElement; - new(): HTMLObjectElement; -} +}; interface HTMLOptGroupElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ readonly text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6004,37 +6044,37 @@ interface HTMLOptGroupElement extends HTMLElement { declare var HTMLOptGroupElement: { prototype: HTMLOptGroupElement; new(): HTMLOptGroupElement; -} +}; interface HTMLOptionElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6043,7 +6083,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -6055,7 +6095,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -6077,12 +6117,12 @@ interface HTMLOutputElement extends HTMLElement { declare var HTMLOutputElement: { prototype: HTMLOutputElement; new(): HTMLOutputElement; -} +}; interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6092,24 +6132,24 @@ interface HTMLParagraphElement extends HTMLElement { declare var HTMLParagraphElement: { prototype: HTMLParagraphElement; new(): HTMLParagraphElement; -} +}; interface HTMLParamElement extends HTMLElement { /** - * Sets or retrieves the name of an input parameter for an element. - */ + * Sets or retrieves the name of an input parameter for an element. + */ name: string; /** - * Sets or retrieves the content type of the resource designated by the value attribute. - */ + * Sets or retrieves the content type of the resource designated by the value attribute. + */ type: string; /** - * Sets or retrieves the value of an input parameter for an element. - */ + * Sets or retrieves the value of an input parameter for an element. + */ value: string; /** - * Sets or retrieves the data type of the value attribute. - */ + * Sets or retrieves the data type of the value attribute. + */ valueType: string; addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6118,7 +6158,7 @@ interface HTMLParamElement extends HTMLElement { declare var HTMLParamElement: { prototype: HTMLParamElement; new(): HTMLParamElement; -} +}; interface HTMLPictureElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6128,12 +6168,12 @@ interface HTMLPictureElement extends HTMLElement { declare var HTMLPictureElement: { prototype: HTMLPictureElement; new(): HTMLPictureElement; -} +}; interface HTMLPreElement extends HTMLElement { /** - * Sets or gets a value that you can use to implement your own width functionality for the object. - */ + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ width: number; addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6142,24 +6182,24 @@ interface HTMLPreElement extends HTMLElement { declare var HTMLPreElement: { prototype: HTMLPreElement; new(): HTMLPreElement; -} +}; interface HTMLProgressElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Defines the maximum, or "done" value for a progress element. - */ + * Defines the maximum, or "done" value for a progress element. + */ max: number; /** - * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). - */ + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ readonly position: number; /** - * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. - */ + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ value: number; addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6168,12 +6208,12 @@ interface HTMLProgressElement extends HTMLElement { declare var HTMLProgressElement: { prototype: HTMLProgressElement; new(): HTMLProgressElement; -} +}; interface HTMLQuoteElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6182,38 +6222,38 @@ interface HTMLQuoteElement extends HTMLElement { declare var HTMLQuoteElement: { prototype: HTMLQuoteElement; new(): HTMLQuoteElement; -} +}; interface HTMLScriptElement extends HTMLElement { async: boolean; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; crossOrigin: string | null; /** - * Sets or retrieves the status of the script. - */ + * Sets or retrieves the status of the script. + */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. - */ + * Sets or retrieves the event for which the script is written. + */ event: string; - /** - * Sets or retrieves the object that is bound to the event script. - */ + /** + * Sets or retrieves the object that is bound to the event script. + */ htmlFor: string; /** - * Retrieves the URL to an external file that contains the source code or data. - */ + * Retrieves the URL to an external file that contains the source code or data. + */ src: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; /** - * Sets or retrieves the MIME type for the associated scripting engine. - */ + * Sets or retrieves the MIME type for the associated scripting engine. + */ type: string; integrity: string; addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6223,94 +6263,94 @@ interface HTMLScriptElement extends HTMLElement { declare var HTMLScriptElement: { prototype: HTMLScriptElement; new(): HTMLScriptElement; -} +}; interface HTMLSelectElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ length: number; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; readonly options: HTMLOptionsCollection; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the index of the selected option in a select object. - */ + * Sets or retrieves the index of the selected option in a select object. + */ selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. - */ + * Sets or retrieves the number of rows in the list box. + */ size: number; /** - * Retrieves the type of select control based on the value of the MULTIPLE attribute. - */ + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Adds an element to the areas, controlRange, or options collection. - * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. - */ + * Adds an element to the areas, controlRange, or options collection. + * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + */ add(element: HTMLElement, before?: HTMLElement | number): void; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a select object or an object from an options collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a select object or an object from an options collection. - * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. - */ + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ namedItem(name: string): any; /** - * Removes an element from the collection. - * @param index Number that specifies the zero-based index of the element to remove from the collection. - */ + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ remove(index?: number): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6320,18 +6360,18 @@ interface HTMLSelectElement extends HTMLElement { declare var HTMLSelectElement: { prototype: HTMLSelectElement; new(): HTMLSelectElement; -} +}; interface HTMLSourceElement extends HTMLElement { /** - * Gets or sets the intended media type of the media source. + * Gets or sets the intended media type of the media source. */ media: string; msKeySystem: string; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** @@ -6345,7 +6385,7 @@ interface HTMLSourceElement extends HTMLElement { declare var HTMLSourceElement: { prototype: HTMLSourceElement; new(): HTMLSourceElement; -} +}; interface HTMLSpanElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6355,17 +6395,17 @@ interface HTMLSpanElement extends HTMLElement { declare var HTMLSpanElement: { prototype: HTMLSpanElement; new(): HTMLSpanElement; -} +}; interface HTMLStyleElement extends HTMLElement, LinkStyle { disabled: boolean; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Retrieves the CSS language in which the style sheet is written. - */ + * Retrieves the CSS language in which the style sheet is written. + */ type: string; addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6374,16 +6414,16 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { declare var HTMLStyleElement: { prototype: HTMLStyleElement; new(): HTMLStyleElement; -} +}; interface HTMLTableCaptionElement extends HTMLElement { /** - * Sets or retrieves the alignment of the caption or legend. - */ + * Sets or retrieves the alignment of the caption or legend. + */ align: string; /** - * Sets or retrieves whether the caption appears at the top or bottom of the table. - */ + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ vAlign: string; addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6392,53 +6432,53 @@ interface HTMLTableCaptionElement extends HTMLElement { declare var HTMLTableCaptionElement: { prototype: HTMLTableCaptionElement; new(): HTMLTableCaptionElement; -} +}; interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves abbreviated text for the object. - */ + * Sets or retrieves abbreviated text for the object. + */ abbr: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. - */ + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ axis: string; bgColor: any; /** - * Retrieves the position of the object in the cells collection of a row. - */ + * Retrieves the position of the object in the cells collection of a row. + */ readonly cellIndex: number; /** - * Sets or retrieves the number columns in the table that the object should span. - */ + * Sets or retrieves the number columns in the table that the object should span. + */ colSpan: number; /** - * Sets or retrieves a list of header cells that provide information for the object. - */ + * Sets or retrieves a list of header cells that provide information for the object. + */ headers: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; /** - * Sets or retrieves how many rows in a table the cell should span. - */ + * Sets or retrieves how many rows in a table the cell should span. + */ rowSpan: number; /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6447,20 +6487,20 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableCellElement: { prototype: HTMLTableCellElement; new(): HTMLTableCellElement; -} +}; interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves the alignment of the object relative to the display or table. - */ + * Sets or retrieves the alignment of the object relative to the display or table. + */ align: string; /** - * Sets or retrieves the number of columns in the group. - */ + * Sets or retrieves the number of columns in the group. + */ span: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: any; addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6469,7 +6509,7 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableColElement: { prototype: HTMLTableColElement; new(): HTMLTableColElement; -} +}; interface HTMLTableDataCellElement extends HTMLTableCellElement { addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6479,111 +6519,111 @@ interface HTMLTableDataCellElement extends HTMLTableCellElement { declare var HTMLTableDataCellElement: { prototype: HTMLTableDataCellElement; new(): HTMLTableDataCellElement; -} +}; interface HTMLTableElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; bgColor: any; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the caption object of a table. - */ + * Retrieves the caption object of a table. + */ caption: HTMLTableCaptionElement; /** - * Sets or retrieves the amount of space between the border of the cell and the content of the cell. - */ + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ cellPadding: string; /** - * Sets or retrieves the amount of space between cells in a table. - */ + * Sets or retrieves the amount of space between cells in a table. + */ cellSpacing: string; /** - * Sets or retrieves the number of columns in the table. - */ + * Sets or retrieves the number of columns in the table. + */ cols: number; /** - * Sets or retrieves the way the border frame around the table is displayed. - */ + * Sets or retrieves the way the border frame around the table is displayed. + */ frame: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Sets or retrieves which dividing lines (inner borders) are displayed. - */ + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ rules: string; /** - * Sets or retrieves a description and/or structure of the object. - */ + * Sets or retrieves a description and/or structure of the object. + */ summary: string; /** - * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. - */ + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ tBodies: HTMLCollectionOf; /** - * Retrieves the tFoot object of the table. - */ + * Retrieves the tFoot object of the table. + */ tFoot: HTMLTableSectionElement; /** - * Retrieves the tHead object of the table. - */ + * Retrieves the tHead object of the table. + */ tHead: HTMLTableSectionElement; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Creates an empty caption element in the table. - */ + * Creates an empty caption element in the table. + */ createCaption(): HTMLTableCaptionElement; /** - * Creates an empty tBody element in the table. - */ + * Creates an empty tBody element in the table. + */ createTBody(): HTMLTableSectionElement; /** - * Creates an empty tFoot element in the table. - */ + * Creates an empty tFoot element in the table. + */ createTFoot(): HTMLTableSectionElement; /** - * Returns the tHead element object if successful, or null otherwise. - */ + * Returns the tHead element object if successful, or null otherwise. + */ createTHead(): HTMLTableSectionElement; /** - * Deletes the caption element and its contents from the table. - */ + * Deletes the caption element and its contents from the table. + */ deleteCaption(): void; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Deletes the tFoot element and its contents from the table. - */ + * Deletes the tFoot element and its contents from the table. + */ deleteTFoot(): void; /** - * Deletes the tHead element and its contents from the table. - */ + * Deletes the tHead element and its contents from the table. + */ deleteTHead(): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6592,12 +6632,12 @@ interface HTMLTableElement extends HTMLElement { declare var HTMLTableElement: { prototype: HTMLTableElement; new(): HTMLTableElement; -} +}; interface HTMLTableHeaderCellElement extends HTMLTableCellElement { /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6606,39 +6646,39 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { declare var HTMLTableHeaderCellElement: { prototype: HTMLTableHeaderCellElement; new(): HTMLTableHeaderCellElement; -} +}; interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; bgColor: any; /** - * Retrieves a collection of all cells in the table row. - */ + * Retrieves a collection of all cells in the table row. + */ cells: HTMLCollectionOf; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Retrieves the position of the object in the rows collection for the table. - */ + * Retrieves the position of the object in the rows collection for the table. + */ readonly rowIndex: number; /** - * Retrieves the position of the object in the collection. - */ + * Retrieves the position of the object in the collection. + */ readonly sectionRowIndex: number; /** - * Removes the specified cell from the table row, as well as from the cells collection. - * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. - */ + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ deleteCell(index?: number): void; /** - * Creates a new cell in the table row, and adds the cell to the cells collection. - * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. - */ + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ insertCell(index?: number): HTMLTableDataCellElement; addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6647,26 +6687,26 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableRowElement: { prototype: HTMLTableRowElement; new(): HTMLTableRowElement; -} +}; interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6675,7 +6715,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -6686,105 +6726,105 @@ interface HTMLTemplateElement extends HTMLElement { declare var HTMLTemplateElement: { prototype: HTMLTemplateElement; new(): HTMLTemplateElement; -} +}; interface HTMLTextAreaElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ cols: number; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; /** - * Sets or retrieves the value indicated whether the content of the object is read-only. - */ + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: number; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; /** - * Sets or retrieves the value indicating whether the control is selected. - */ + * Sets or retrieves the value indicating whether the control is selected. + */ status: any; /** - * Retrieves the type of control. - */ + * Retrieves the type of control. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Retrieves or sets the text in the entry field of the textArea element. - */ + * Retrieves or sets the text in the entry field of the textArea element. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Sets or retrieves how to handle wordwrapping in the object. - */ + * Sets or retrieves how to handle wordwrapping in the object. + */ wrap: string; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Highlights the input area of a form element. - */ + * Highlights the input area of a form element. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start: number, end: number): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6793,7 +6833,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -6804,12 +6844,12 @@ interface HTMLTimeElement extends HTMLElement { declare var HTMLTimeElement: { prototype: HTMLTimeElement; new(): HTMLTimeElement; -} +}; interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6818,7 +6858,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -6843,7 +6883,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -6855,7 +6895,7 @@ interface HTMLUListElement extends HTMLElement { declare var HTMLUListElement: { prototype: HTMLUListElement; new(): HTMLUListElement; -} +}; interface HTMLUnknownElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6865,7 +6905,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -6875,8 +6915,8 @@ interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { interface HTMLVideoElement extends HTMLMediaElement { /** - * Gets or sets the height of the video element. - */ + * Gets or sets the height of the video element. + */ height: number; msHorizontalMirror: boolean; readonly msIsLayoutOptimalForPlayback: boolean; @@ -6888,31 +6928,31 @@ interface HTMLVideoElement extends HTMLMediaElement { onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; /** - * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. - */ + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ poster: string; /** - * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoHeight: number; /** - * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoWidth: number; readonly webkitDisplayingFullscreen: boolean; readonly webkitSupportsFullscreen: boolean; /** - * Gets or sets the width of the video element. - */ + * Gets or sets the width of the video element. + */ width: number; getVideoPlaybackQuality(): VideoPlaybackQuality; msFrameStep(forward: boolean): void; msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; - webkitEnterFullScreen(): void; webkitEnterFullscreen(): void; - webkitExitFullScreen(): void; + webkitEnterFullScreen(): void; webkitExitFullscreen(): void; + webkitExitFullScreen(): void; addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6920,47 +6960,7 @@ interface HTMLVideoElement extends HTMLMediaElement { declare var HTMLVideoElement: { prototype: HTMLVideoElement; new(): HTMLVideoElement; -} - -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; -} - -declare var HashChangeEvent: { - prototype: HashChangeEvent; - new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; -} - -interface Headers { - append(name: string, value: string): void; - delete(name: string): void; - forEach(callback: ForEachCallback): void; - get(name: string): string | null; - has(name: string): boolean; - set(name: string, value: string): void; -} - -declare var Headers: { - prototype: Headers; - new(init?: any): Headers; -} - -interface History { - readonly length: number; - readonly state: any; - scrollRestoration: ScrollRestoration; - back(): void; - forward(): void; - go(delta?: number): void; - pushState(data: any, title: string, url?: string | null): void; - replaceState(data: any, title: string, url?: string | null): void; -} - -declare var History: { - prototype: History; - new(): History; -} +}; interface IDBCursor { readonly direction: IDBCursorDirection; @@ -6984,7 +6984,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -6993,7 +6993,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -7010,7 +7010,7 @@ interface IDBDatabase extends EventTarget { close(): void; createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -7019,7 +7019,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -7030,7 +7030,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -7041,14 +7041,14 @@ interface IDBIndex { count(key?: IDBKeyRange | IDBValidKey): IDBRequest; get(key: IDBKeyRange | IDBValidKey): IDBRequest; getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { prototype: IDBIndex; new(): IDBIndex; -} +}; interface IDBKeyRange { readonly lower: any; @@ -7064,7 +7064,7 @@ declare var IDBKeyRange: { lowerBound(lower: any, open?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; upperBound(upper: any, open?: boolean): IDBKeyRange; -} +}; interface IDBObjectStore { readonly indexNames: DOMStringList; @@ -7080,14 +7080,14 @@ interface IDBObjectStore { deleteIndex(indexName: string): void; get(key: any): IDBRequest; index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; new(): IDBObjectStore; -} +}; interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { "blocked": Event; @@ -7104,7 +7104,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -7112,7 +7112,7 @@ interface IDBRequestEventMap { } interface IDBRequest extends EventTarget { - readonly error: DOMError; + readonly error: DOMException; onerror: (this: IDBRequest, ev: Event) => any; onsuccess: (this: IDBRequest, ev: Event) => any; readonly readyState: IDBRequestReadyState; @@ -7126,7 +7126,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -7136,7 +7136,7 @@ interface IDBTransactionEventMap { interface IDBTransaction extends EventTarget { readonly db: IDBDatabase; - readonly error: DOMError; + readonly error: DOMException; readonly mode: IDBTransactionMode; onabort: (this: IDBTransaction, ev: Event) => any; oncomplete: (this: IDBTransaction, ev: Event) => any; @@ -7156,7 +7156,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -7166,7 +7166,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -7175,7 +7175,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -7187,7 +7187,7 @@ declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} +}; interface IntersectionObserver { readonly root: Element | null; @@ -7202,7 +7202,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -7216,7 +7216,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -7251,7 +7251,7 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_NUMPAD: number; readonly DOM_KEY_LOCATION_RIGHT: number; readonly DOM_KEY_LOCATION_STANDARD: number; -} +}; interface ListeningStateChangedEvent extends Event { readonly label: string; @@ -7261,7 +7261,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -7282,7 +7282,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -7292,8 +7292,390 @@ interface LongRunningScriptDetectedEvent extends Event { declare var LongRunningScriptDetectedEvent: { prototype: LongRunningScriptDetectedEvent; new(): LongRunningScriptDetectedEvent; +}; + +interface MediaDeviceInfo { + readonly deviceId: string; + readonly groupId: string; + readonly kind: MediaDeviceKind; + readonly label: string; } +declare var MediaDeviceInfo: { + prototype: MediaDeviceInfo; + new(): MediaDeviceInfo; +}; + +interface MediaDevicesEventMap { + "devicechange": Event; +} + +interface MediaDevices extends EventTarget { + ondevicechange: (this: MediaDevices, ev: Event) => any; + enumerateDevices(): any; + getSupportedConstraints(): MediaTrackSupportedConstraints; + getUserMedia(constraints: MediaStreamConstraints): Promise; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaDevices: { + prototype: MediaDevices; + new(): MediaDevices; +}; + +interface MediaElementAudioSourceNode extends AudioNode { +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(): MediaElementAudioSourceNode; +}; + +interface MediaEncryptedEvent extends Event { + readonly initData: ArrayBuffer | null; + readonly initDataType: string; +} + +declare var MediaEncryptedEvent: { + prototype: MediaEncryptedEvent; + new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; +}; + +interface MediaError { + readonly code: number; + readonly msExtendedCode: number; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +}; + +interface MediaKeyMessageEvent extends Event { + readonly message: ArrayBuffer; + readonly messageType: MediaKeyMessageType; +} + +declare var MediaKeyMessageEvent: { + prototype: MediaKeyMessageEvent; + new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; +}; + +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: any): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + +interface MediaKeySession extends EventTarget { + readonly closed: Promise; + readonly expiration: number; + readonly keyStatuses: MediaKeyStatusMap; + readonly sessionId: string; + close(): Promise; + generateRequest(initDataType: string, initData: any): Promise; + load(sessionId: string): Promise; + remove(): Promise; + update(response: any): Promise; +} + +declare var MediaKeySession: { + prototype: MediaKeySession; + new(): MediaKeySession; +}; + +interface MediaKeyStatusMap { + readonly size: number; + forEach(callback: ForEachCallback): void; + get(keyId: any): MediaKeyStatus; + has(keyId: any): boolean; +} + +declare var MediaKeyStatusMap: { + prototype: MediaKeyStatusMap; + new(): MediaKeyStatusMap; +}; + +interface MediaKeySystemAccess { + readonly keySystem: string; + createMediaKeys(): Promise; + getConfiguration(): MediaKeySystemConfiguration; +} + +declare var MediaKeySystemAccess: { + prototype: MediaKeySystemAccess; + new(): MediaKeySystemAccess; +}; + +interface MediaList { + readonly length: number; + mediaText: string; + appendMedium(newMedium: string): void; + deleteMedium(oldMedium: string): void; + item(index: number): string; + toString(): string; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +}; + +interface MediaQueryList { + readonly matches: boolean; + readonly media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +}; + +interface MediaSource extends EventTarget { + readonly activeSourceBuffers: SourceBufferList; + duration: number; + readonly readyState: string; + readonly sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: number): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +}; + +interface MediaStreamEventMap { + "active": Event; + "addtrack": MediaStreamTrackEvent; + "inactive": Event; + "removetrack": MediaStreamTrackEvent; +} + +interface MediaStream extends EventTarget { + readonly active: boolean; + readonly id: string; + onactive: (this: MediaStream, ev: Event) => any; + onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + oninactive: (this: MediaStream, ev: Event) => any; + onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + addTrack(track: MediaStreamTrack): void; + clone(): MediaStream; + getAudioTracks(): MediaStreamTrack[]; + getTrackById(trackId: string): MediaStreamTrack | null; + getTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + removeTrack(track: MediaStreamTrack): void; + stop(): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStream: { + prototype: MediaStream; + new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; +}; + +interface MediaStreamAudioSourceNode extends AudioNode { +} + +declare var MediaStreamAudioSourceNode: { + prototype: MediaStreamAudioSourceNode; + new(): MediaStreamAudioSourceNode; +}; + +interface MediaStreamError { + readonly constraintName: string | null; + readonly message: string | null; + readonly name: string; +} + +declare var MediaStreamError: { + prototype: MediaStreamError; + new(): MediaStreamError; +}; + +interface MediaStreamErrorEvent extends Event { + readonly error: MediaStreamError | null; +} + +declare var MediaStreamErrorEvent: { + prototype: MediaStreamErrorEvent; + new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; +}; + +interface MediaStreamEvent extends Event { + readonly stream: MediaStream | null; +} + +declare var MediaStreamEvent: { + prototype: MediaStreamEvent; + new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; +}; + +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + +interface MediaStreamTrack extends EventTarget { + enabled: boolean; + readonly id: string; + readonly kind: string; + readonly label: string; + readonly muted: boolean; + onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onmute: (this: MediaStreamTrack, ev: Event) => any; + onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onunmute: (this: MediaStreamTrack, ev: Event) => any; + readonly readonly: boolean; + readonly readyState: MediaStreamTrackState; + readonly remote: boolean; + applyConstraints(constraints: MediaTrackConstraints): Promise; + clone(): MediaStreamTrack; + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + stop(): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new(): MediaStreamTrack; +}; + +interface MediaStreamTrackEvent extends Event { + readonly track: MediaStreamTrack; +} + +declare var MediaStreamTrackEvent: { + prototype: MediaStreamTrackEvent; + new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; +}; + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +}; + +interface MessageEvent extends Event { + readonly data: any; + readonly origin: string; + readonly ports: any; + readonly source: Window; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +}; + +interface MessagePortEventMap { + "message": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (this: MessagePort, ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, transfer?: any[]): void; + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +}; + +interface MimeType { + readonly description: string; + readonly enabledPlugin: Plugin; + readonly suffixes: string; + readonly type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +}; + +interface MimeTypeArray { + readonly length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +}; + +interface MouseEvent extends UIEvent { + readonly altKey: boolean; + readonly button: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; + readonly ctrlKey: boolean; + readonly fromElement: Element; + readonly layerX: number; + readonly layerY: number; + readonly metaKey: boolean; + readonly movementX: number; + readonly movementY: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pageX: number; + readonly pageY: number; + readonly relatedTarget: EventTarget; + readonly screenX: number; + readonly screenY: number; + readonly shiftKey: boolean; + readonly toElement: Element; + readonly which: number; + readonly x: number; + readonly y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +}; + interface MSApp { clearTemporaryWebDataAsync(): MSAppAsyncOperation; createBlobFromRandomAccessStream(type: string, seeker: any): Blob; @@ -7342,7 +7724,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -7352,7 +7734,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -7362,7 +7744,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -7372,7 +7754,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -7384,7 +7766,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -7395,7 +7777,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -7404,7 +7786,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -7415,7 +7797,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -7451,7 +7833,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -7461,7 +7843,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -7495,7 +7877,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -7521,7 +7903,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -7550,7 +7932,7 @@ declare var MSManipulationEvent: { readonly MS_MANIPULATION_STATE_PRESELECT: number; readonly MS_MANIPULATION_STATE_SELECTING: number; readonly MS_MANIPULATION_STATE_STOPPED: number; -} +}; interface MSMediaKeyError { readonly code: number; @@ -7572,7 +7954,7 @@ declare var MSMediaKeyError: { readonly MS_MEDIA_KEYERR_OUTPUT: number; readonly MS_MEDIA_KEYERR_SERVICE: number; readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} +}; interface MSMediaKeyMessageEvent extends Event { readonly destinationURL: string | null; @@ -7582,7 +7964,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -7591,8 +7973,20 @@ interface MSMediaKeyNeededEvent extends Event { declare var MSMediaKeyNeededEvent: { prototype: MSMediaKeyNeededEvent; new(): MSMediaKeyNeededEvent; +}; + +interface MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; } +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string): string; +}; + interface MSMediaKeySession extends EventTarget { readonly error: MSMediaKeyError | null; readonly keySystem: string; @@ -7604,19 +7998,7 @@ interface MSMediaKeySession extends EventTarget { declare var MSMediaKeySession: { prototype: MSMediaKeySession; new(): MSMediaKeySession; -} - -interface MSMediaKeys { - readonly keySystem: string; - createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; -} - -declare var MSMediaKeys: { - prototype: MSMediaKeys; - new(keySystem: string): MSMediaKeys; - isTypeSupported(keySystem: string, type?: string): boolean; - isTypeSupportedWithFeatures(keySystem: string, type?: string): string; -} +}; interface MSPointerEvent extends MouseEvent { readonly currentPoint: any; @@ -7639,7 +8021,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -7650,7 +8032,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -7660,7 +8042,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -7671,7 +8053,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -7687,7 +8069,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -7722,7 +8104,7 @@ declare var MSWebViewAsyncOperation: { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; -} +}; interface MSWebViewSettings { isIndexedDBEnabled: boolean; @@ -7732,389 +8114,7 @@ interface MSWebViewSettings { declare var MSWebViewSettings: { prototype: MSWebViewSettings; new(): MSWebViewSettings; -} - -interface MediaDeviceInfo { - readonly deviceId: string; - readonly groupId: string; - readonly kind: MediaDeviceKind; - readonly label: string; -} - -declare var MediaDeviceInfo: { - prototype: MediaDeviceInfo; - new(): MediaDeviceInfo; -} - -interface MediaDevicesEventMap { - "devicechange": Event; -} - -interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; - getSupportedConstraints(): MediaTrackSupportedConstraints; - getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaDevices: { - prototype: MediaDevices; - new(): MediaDevices; -} - -interface MediaElementAudioSourceNode extends AudioNode { -} - -declare var MediaElementAudioSourceNode: { - prototype: MediaElementAudioSourceNode; - new(): MediaElementAudioSourceNode; -} - -interface MediaEncryptedEvent extends Event { - readonly initData: ArrayBuffer | null; - readonly initDataType: string; -} - -declare var MediaEncryptedEvent: { - prototype: MediaEncryptedEvent; - new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; -} - -interface MediaError { - readonly code: number; - readonly msExtendedCode: number; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -declare var MediaError: { - prototype: MediaError; - new(): MediaError; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -interface MediaKeyMessageEvent extends Event { - readonly message: ArrayBuffer; - readonly messageType: MediaKeyMessageType; -} - -declare var MediaKeyMessageEvent: { - prototype: MediaKeyMessageEvent; - new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; -} - -interface MediaKeySession extends EventTarget { - readonly closed: Promise; - readonly expiration: number; - readonly keyStatuses: MediaKeyStatusMap; - readonly sessionId: string; - close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; - load(sessionId: string): Promise; - remove(): Promise; - update(response: any): Promise; -} - -declare var MediaKeySession: { - prototype: MediaKeySession; - new(): MediaKeySession; -} - -interface MediaKeyStatusMap { - readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; -} - -declare var MediaKeyStatusMap: { - prototype: MediaKeyStatusMap; - new(): MediaKeyStatusMap; -} - -interface MediaKeySystemAccess { - readonly keySystem: string; - createMediaKeys(): Promise; - getConfiguration(): MediaKeySystemConfiguration; -} - -declare var MediaKeySystemAccess: { - prototype: MediaKeySystemAccess; - new(): MediaKeySystemAccess; -} - -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; -} - -declare var MediaKeys: { - prototype: MediaKeys; - new(): MediaKeys; -} - -interface MediaList { - readonly length: number; - mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; - [index: number]: string; -} - -declare var MediaList: { - prototype: MediaList; - new(): MediaList; -} - -interface MediaQueryList { - readonly matches: boolean; - readonly media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; -} - -declare var MediaQueryList: { - prototype: MediaQueryList; - new(): MediaQueryList; -} - -interface MediaSource extends EventTarget { - readonly activeSourceBuffers: SourceBufferList; - duration: number; - readonly readyState: string; - readonly sourceBuffers: SourceBufferList; - addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: number): void; - removeSourceBuffer(sourceBuffer: SourceBuffer): void; -} - -declare var MediaSource: { - prototype: MediaSource; - new(): MediaSource; - isTypeSupported(type: string): boolean; -} - -interface MediaStreamEventMap { - "active": Event; - "addtrack": MediaStreamTrackEvent; - "inactive": Event; - "removetrack": MediaStreamTrackEvent; -} - -interface MediaStream extends EventTarget { - readonly active: boolean; - readonly id: string; - onactive: (this: MediaStream, ev: Event) => any; - onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - oninactive: (this: MediaStream, ev: Event) => any; - onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - addTrack(track: MediaStreamTrack): void; - clone(): MediaStream; - getAudioTracks(): MediaStreamTrack[]; - getTrackById(trackId: string): MediaStreamTrack | null; - getTracks(): MediaStreamTrack[]; - getVideoTracks(): MediaStreamTrack[]; - removeTrack(track: MediaStreamTrack): void; - stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStream: { - prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; -} - -interface MediaStreamAudioSourceNode extends AudioNode { -} - -declare var MediaStreamAudioSourceNode: { - prototype: MediaStreamAudioSourceNode; - new(): MediaStreamAudioSourceNode; -} - -interface MediaStreamError { - readonly constraintName: string | null; - readonly message: string | null; - readonly name: string; -} - -declare var MediaStreamError: { - prototype: MediaStreamError; - new(): MediaStreamError; -} - -interface MediaStreamErrorEvent extends Event { - readonly error: MediaStreamError | null; -} - -declare var MediaStreamErrorEvent: { - prototype: MediaStreamErrorEvent; - new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; -} - -interface MediaStreamEvent extends Event { - readonly stream: MediaStream | null; -} - -declare var MediaStreamEvent: { - prototype: MediaStreamEvent; - new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; -} - -interface MediaStreamTrackEventMap { - "ended": MediaStreamErrorEvent; - "mute": Event; - "overconstrained": MediaStreamErrorEvent; - "unmute": Event; -} - -interface MediaStreamTrack extends EventTarget { - enabled: boolean; - readonly id: string; - readonly kind: string; - readonly label: string; - readonly muted: boolean; - onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onmute: (this: MediaStreamTrack, ev: Event) => any; - onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onunmute: (this: MediaStreamTrack, ev: Event) => any; - readonly readonly: boolean; - readonly readyState: MediaStreamTrackState; - readonly remote: boolean; - applyConstraints(constraints: MediaTrackConstraints): Promise; - clone(): MediaStreamTrack; - getCapabilities(): MediaTrackCapabilities; - getConstraints(): MediaTrackConstraints; - getSettings(): MediaTrackSettings; - stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new(): MediaStreamTrack; -} - -interface MediaStreamTrackEvent extends Event { - readonly track: MediaStreamTrack; -} - -declare var MediaStreamTrackEvent: { - prototype: MediaStreamTrackEvent; - new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; -} - -interface MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; -} - -declare var MessageChannel: { - prototype: MessageChannel; - new(): MessageChannel; -} - -interface MessageEvent extends Event { - readonly data: any; - readonly origin: string; - readonly ports: any; - readonly source: Window; - initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; -} - -declare var MessageEvent: { - prototype: MessageEvent; - new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} - -interface MessagePortEventMap { - "message": MessageEvent; -} - -interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; - close(): void; - postMessage(message?: any, transfer?: any[]): void; - start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MessagePort: { - prototype: MessagePort; - new(): MessagePort; -} - -interface MimeType { - readonly description: string; - readonly enabledPlugin: Plugin; - readonly suffixes: string; - readonly type: string; -} - -declare var MimeType: { - prototype: MimeType; - new(): MimeType; -} - -interface MimeTypeArray { - readonly length: number; - item(index: number): Plugin; - namedItem(type: string): Plugin; - [index: number]: Plugin; -} - -declare var MimeTypeArray: { - prototype: MimeTypeArray; - new(): MimeTypeArray; -} - -interface MouseEvent extends UIEvent { - readonly altKey: boolean; - readonly button: number; - readonly buttons: number; - readonly clientX: number; - readonly clientY: number; - readonly ctrlKey: boolean; - readonly fromElement: Element; - readonly layerX: number; - readonly layerY: number; - readonly metaKey: boolean; - readonly movementX: number; - readonly movementY: number; - readonly offsetX: number; - readonly offsetY: number; - readonly pageX: number; - readonly pageY: number; - readonly relatedTarget: EventTarget; - readonly screenX: number; - readonly screenY: number; - readonly shiftKey: boolean; - readonly toElement: Element; - readonly which: number; - readonly x: number; - readonly y: number; - getModifierState(keyArg: string): boolean; - initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; -} - -declare var MouseEvent: { - prototype: MouseEvent; - new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; -} +}; interface MutationEvent extends Event { readonly attrChange: number; @@ -8134,7 +8134,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -8145,7 +8145,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -8162,7 +8162,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -8179,7 +8179,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -8189,7 +8189,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -8198,7 +8198,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -8207,7 +8207,7 @@ interface NavigationEventWithReferrer extends NavigationEvent { declare var NavigationEventWithReferrer: { prototype: NavigationEventWithReferrer; new(): NavigationEventWithReferrer; -} +}; interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia { readonly authentication: WebAuthentication; @@ -8234,7 +8234,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -8309,7 +8309,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -8332,7 +8332,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -8347,7 +8347,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -8358,7 +8358,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -8388,7 +8388,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -8396,7 +8396,7 @@ interface OES_element_index_uint { declare var OES_element_index_uint: { prototype: OES_element_index_uint; new(): OES_element_index_uint; -} +}; interface OES_standard_derivatives { readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; @@ -8406,7 +8406,7 @@ declare var OES_standard_derivatives: { prototype: OES_standard_derivatives; new(): OES_standard_derivatives; readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} +}; interface OES_texture_float { } @@ -8414,7 +8414,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -8422,7 +8422,7 @@ interface OES_texture_float_linear { declare var OES_texture_float_linear: { prototype: OES_texture_float_linear; new(): OES_texture_float_linear; -} +}; interface OES_texture_half_float { readonly HALF_FLOAT_OES: number; @@ -8432,7 +8432,7 @@ declare var OES_texture_half_float: { prototype: OES_texture_half_float; new(): OES_texture_half_float; readonly HALF_FLOAT_OES: number; -} +}; interface OES_texture_half_float_linear { } @@ -8440,7 +8440,7 @@ interface OES_texture_half_float_linear { declare var OES_texture_half_float_linear: { prototype: OES_texture_half_float_linear; new(): OES_texture_half_float_linear; -} +}; interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; @@ -8449,7 +8449,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -8467,7 +8467,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -8488,7 +8488,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -8505,7 +8505,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -8514,7 +8514,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -8533,7 +8533,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -8541,7 +8541,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -8561,7 +8561,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -8583,7 +8583,7 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; -} +}; interface PaymentRequestUpdateEvent extends Event { updateWith(d: Promise): void; @@ -8592,7 +8592,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -8609,8 +8609,158 @@ interface PaymentResponse { declare var PaymentResponse: { prototype: PaymentResponse; new(): PaymentResponse; +}; + +interface Performance { + readonly navigation: PerformanceNavigation; + readonly timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): any; + getEntriesByName(name: string, entryType?: string): any; + getEntriesByType(entryType: string): any; + getMarks(markName?: string): any; + getMeasures(measureName?: string): any; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; } +declare var Performance: { + prototype: Performance; + new(): Performance; +}; + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +}; + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +}; + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +}; + +interface PerformanceNavigation { + readonly redirectCount: number; + readonly type: number; + toJSON(): any; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +}; + +interface PerformanceNavigationTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly navigationStart: number; + readonly redirectCount: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly type: NavigationType; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +}; + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +}; + +interface PerformanceTiming { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly msFirstPaint: number; + readonly navigationStart: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + readonly secureConnectionStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +}; + interface PerfWidgetExternal { readonly activeNetworkRequestCount: number; readonly averageFrameTime: number; @@ -8638,157 +8788,7 @@ interface PerfWidgetExternal { declare var PerfWidgetExternal: { prototype: PerfWidgetExternal; new(): PerfWidgetExternal; -} - -interface Performance { - readonly navigation: PerformanceNavigation; - readonly timing: PerformanceTiming; - clearMarks(markName?: string): void; - clearMeasures(measureName?: string): void; - clearResourceTimings(): void; - getEntries(): any; - getEntriesByName(name: string, entryType?: string): any; - getEntriesByType(entryType: string): any; - getMarks(markName?: string): any; - getMeasures(measureName?: string): any; - mark(markName: string): void; - measure(measureName: string, startMarkName?: string, endMarkName?: string): void; - now(): number; - setResourceTimingBufferSize(maxSize: number): void; - toJSON(): any; -} - -declare var Performance: { - prototype: Performance; - new(): Performance; -} - -interface PerformanceEntry { - readonly duration: number; - readonly entryType: string; - readonly name: string; - readonly startTime: number; -} - -declare var PerformanceEntry: { - prototype: PerformanceEntry; - new(): PerformanceEntry; -} - -interface PerformanceMark extends PerformanceEntry { -} - -declare var PerformanceMark: { - prototype: PerformanceMark; - new(): PerformanceMark; -} - -interface PerformanceMeasure extends PerformanceEntry { -} - -declare var PerformanceMeasure: { - prototype: PerformanceMeasure; - new(): PerformanceMeasure; -} - -interface PerformanceNavigation { - readonly redirectCount: number; - readonly type: number; - toJSON(): any; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -declare var PerformanceNavigation: { - prototype: PerformanceNavigation; - new(): PerformanceNavigation; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -interface PerformanceNavigationTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly navigationStart: number; - readonly redirectCount: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly type: NavigationType; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; -} - -declare var PerformanceNavigationTiming: { - prototype: PerformanceNavigationTiming; - new(): PerformanceNavigationTiming; -} - -interface PerformanceResourceTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly initiatorType: string; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; -} - -declare var PerformanceResourceTiming: { - prototype: PerformanceResourceTiming; - new(): PerformanceResourceTiming; -} - -interface PerformanceTiming { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly msFirstPaint: number; - readonly navigationStart: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; - readonly secureConnectionStart: number; - toJSON(): any; -} - -declare var PerformanceTiming: { - prototype: PerformanceTiming; - new(): PerformanceTiming; -} +}; interface PeriodicWave { } @@ -8796,7 +8796,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -8806,7 +8806,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -8815,7 +8815,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -8831,7 +8831,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -8844,7 +8844,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -8867,7 +8867,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -8877,7 +8877,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -8887,7 +8887,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -8904,7 +8904,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -8913,7 +8913,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -8925,7 +8925,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -8936,7 +8936,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -8949,7 +8949,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -8959,17 +8959,114 @@ interface PushSubscriptionOptions { declare var PushSubscriptionOptions: { prototype: PushSubscriptionOptions; new(): PushSubscriptionOptions; +}; + +interface Range { + readonly collapsed: boolean; + readonly commonAncestorContainer: Node; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + expand(Unit: ExpandGranularity): boolean; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + insertNode(newNode: Node): void; + selectNode(refNode: Node): void; + selectNodeContents(refNode: Node): void; + setEnd(refNode: Node, offset: number): void; + setEndAfter(refNode: Node): void; + setEndBefore(refNode: Node): void; + setStart(refNode: Node, offset: number): void; + setStartAfter(refNode: Node): void; + setStartBefore(refNode: Node): void; + surroundContents(newParent: Node): void; + toString(): string; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; } -interface RTCDTMFToneChangeEvent extends Event { - readonly tone: string; +declare var Range: { + prototype: Range; + new(): Range; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +}; + +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -declare var RTCDTMFToneChangeEvent: { - prototype: RTCDTMFToneChangeEvent; - new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; +}; + +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; +}; + +interface Request extends Object, Body { + readonly cache: RequestCache; + readonly credentials: RequestCredentials; + readonly destination: RequestDestination; + readonly headers: Headers; + readonly integrity: string; + readonly keepalive: boolean; + readonly method: string; + readonly mode: RequestMode; + readonly redirect: RequestRedirect; + readonly referrer: string; + readonly referrerPolicy: ReferrerPolicy; + readonly type: RequestType; + readonly url: string; + clone(): Request; +} + +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; +}; + +interface Response extends Object, Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; +} + +declare var Response: { + prototype: Response; + new(body?: any, init?: ResponseInit): Response; + error: () => Response; + redirect: (url: string, status?: number) => Response; +}; + interface RTCDtlsTransportEventMap { "dtlsstatechange": RTCDtlsTransportStateChangedEvent; "error": Event; @@ -8992,7 +9089,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -9001,7 +9098,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -9022,19 +9119,28 @@ interface RTCDtmfSender extends EventTarget { declare var RTCDtmfSender: { prototype: RTCDtmfSender; new(sender: RTCRtpSender): RTCDtmfSender; +}; + +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +}; + interface RTCIceCandidate { candidate: string | null; - sdpMLineIndex: number | null; sdpMid: string | null; + sdpMLineIndex: number | null; toJSON(): any; } declare var RTCIceCandidate: { prototype: RTCIceCandidate; new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate; -} +}; interface RTCIceCandidatePairChangedEvent extends Event { readonly pair: RTCIceCandidatePair; @@ -9043,7 +9149,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -9064,7 +9170,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -9073,7 +9179,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -9102,7 +9208,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -9111,7 +9217,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -9157,7 +9263,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -9166,7 +9272,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -9190,7 +9296,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -9215,7 +9321,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -9226,7 +9332,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -9243,7 +9349,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -9252,7 +9358,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -9262,112 +9368,421 @@ interface RTCStatsProvider extends EventTarget { declare var RTCStatsProvider: { prototype: RTCStatsProvider; new(): RTCStatsProvider; +}; + +interface ScopedCredential { + readonly id: ArrayBuffer; + readonly type: ScopedCredentialType; } -interface Range { - readonly collapsed: boolean; - readonly commonAncestorContainer: Node; - readonly endContainer: Node; - readonly endOffset: number; - readonly startContainer: Node; - readonly startOffset: number; - cloneContents(): DocumentFragment; - cloneRange(): Range; - collapse(toStart: boolean): void; - compareBoundaryPoints(how: number, sourceRange: Range): number; - createContextualFragment(fragment: string): DocumentFragment; - deleteContents(): void; - detach(): void; - expand(Unit: ExpandGranularity): boolean; - extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - insertNode(newNode: Node): void; - selectNode(refNode: Node): void; - selectNodeContents(refNode: Node): void; - setEnd(refNode: Node, offset: number): void; - setEndAfter(refNode: Node): void; - setEndBefore(refNode: Node): void; - setStart(refNode: Node, offset: number): void; - setStartAfter(refNode: Node): void; - setStartBefore(refNode: Node): void; - surroundContents(newParent: Node): void; +declare var ScopedCredential: { + prototype: ScopedCredential; + new(): ScopedCredential; +}; + +interface ScopedCredentialInfo { + readonly credential: ScopedCredential; + readonly publicKey: CryptoKey; +} + +declare var ScopedCredentialInfo: { + prototype: ScopedCredentialInfo; + new(): ScopedCredentialInfo; +}; + +interface ScreenEventMap { + "MSOrientationChange": Event; +} + +interface Screen extends EventTarget { + readonly availHeight: number; + readonly availWidth: number; + bufferDepth: number; + readonly colorDepth: number; + readonly deviceXDPI: number; + readonly deviceYDPI: number; + readonly fontSmoothingEnabled: boolean; + readonly height: number; + readonly logicalXDPI: number; + readonly logicalYDPI: number; + readonly msOrientation: string; + onmsorientationchange: (this: Screen, ev: Event) => any; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +}; + +interface ScriptNotifyEvent extends Event { + readonly callingUri: string; + readonly value: string; +} + +declare var ScriptNotifyEvent: { + prototype: ScriptNotifyEvent; + new(): ScriptNotifyEvent; +}; + +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + readonly bufferSize: number; + onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +}; + +interface Selection { + readonly anchorNode: Node; + readonly anchorOffset: number; + readonly baseNode: Node; + readonly baseOffset: number; + readonly extentNode: Node; + readonly extentOffset: number; + readonly focusNode: Node; + readonly focusOffset: number; + readonly isCollapsed: boolean; + readonly rangeCount: number; + readonly type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + setPosition(parentNode: Node, offset: number): void; toString(): string; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; } -declare var Range: { - prototype: Range; - new(): Range; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; +declare var Selection: { + prototype: Selection; + new(): Selection; +}; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; } -interface ReadableStream { - readonly locked: boolean; - cancel(): Promise; - getReader(): ReadableStreamReader; +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: (this: ServiceWorker, ev: Event) => any; + readonly scriptURL: USVString; + readonly state: ServiceWorkerState; + postMessage(message: any, transfer?: any[]): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStream: { - prototype: ReadableStream; - new(): ReadableStream; +declare var ServiceWorker: { + prototype: ServiceWorker; + new(): ServiceWorker; +}; + +interface ServiceWorkerContainerEventMap { + "controllerchange": Event; + "message": ServiceWorkerMessageEvent; } -interface ReadableStreamReader { - cancel(): Promise; - read(): Promise; - releaseLock(): void; +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; + onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; + readonly ready: Promise; + getRegistration(clientURL?: USVString): Promise; + getRegistrations(): any; + register(scriptURL: USVString, options?: RegistrationOptions): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStreamReader: { - prototype: ReadableStreamReader; - new(): ReadableStreamReader; +declare var ServiceWorkerContainer: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: MessagePort[] | null; + readonly source: ServiceWorker | MessagePort | null; } -interface Request extends Object, Body { - readonly cache: RequestCache; - readonly credentials: RequestCredentials; - readonly destination: RequestDestination; - readonly headers: Headers; - readonly integrity: string; - readonly keepalive: boolean; - readonly method: string; - readonly mode: RequestMode; - readonly redirect: RequestRedirect; - readonly referrer: string; - readonly referrerPolicy: ReferrerPolicy; - readonly type: RequestType; +declare var ServiceWorkerMessageEvent: { + prototype: ServiceWorkerMessageEvent; + new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; +}; + +interface ServiceWorkerRegistrationEventMap { + "updatefound": Event; +} + +interface ServiceWorkerRegistration extends EventTarget { + readonly active: ServiceWorker | null; + readonly installing: ServiceWorker | null; + onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; + readonly pushManager: PushManager; + readonly scope: USVString; + readonly sync: SyncManager; + readonly waiting: ServiceWorker | null; + getNotifications(filter?: GetNotificationOptions): any; + showNotification(title: string, options?: NotificationOptions): Promise; + unregister(): Promise; + update(): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ServiceWorkerRegistration: { + prototype: ServiceWorkerRegistration; + new(): ServiceWorkerRegistration; +}; + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + readonly audioTracks: AudioTrackList; + readonly buffered: TimeRanges; + mode: AppendMode; + timestampOffset: number; + readonly updating: boolean; + readonly videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | ArrayBufferView): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +}; + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +}; + +interface SpeechSynthesisEventMap { + "voiceschanged": Event; +} + +interface SpeechSynthesis extends EventTarget { + onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; + readonly paused: boolean; + readonly pending: boolean; + readonly speaking: boolean; + cancel(): void; + getVoices(): SpeechSynthesisVoice[]; + pause(): void; + resume(): void; + speak(utterance: SpeechSynthesisUtterance): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesis: { + prototype: SpeechSynthesis; + new(): SpeechSynthesis; +}; + +interface SpeechSynthesisEvent extends Event { + readonly charIndex: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance | null; +} + +declare var SpeechSynthesisEvent: { + prototype: SpeechSynthesisEvent; + new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; +}; + +interface SpeechSynthesisUtteranceEventMap { + "boundary": Event; + "end": Event; + "error": Event; + "mark": Event; + "pause": Event; + "resume": Event; + "start": Event; +} + +interface SpeechSynthesisUtterance extends EventTarget { + lang: string; + onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; + onend: (this: SpeechSynthesisUtterance, ev: Event) => any; + onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; + onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; + onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; + onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; + onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; + pitch: number; + rate: number; + text: string; + voice: SpeechSynthesisVoice; + volume: number; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesisUtterance: { + prototype: SpeechSynthesisUtterance; + new(text?: string): SpeechSynthesisUtterance; +}; + +interface SpeechSynthesisVoice { + readonly default: boolean; + readonly lang: string; + readonly localService: boolean; + readonly name: string; + readonly voiceURI: string; +} + +declare var SpeechSynthesisVoice: { + prototype: SpeechSynthesisVoice; + new(): SpeechSynthesisVoice; +}; + +interface StereoPannerNode extends AudioNode { + readonly pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(): StereoPannerNode; +}; + +interface Storage { + readonly length: number; + clear(): void; + getItem(key: string): string | null; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, data: string): void; + [key: string]: any; + [index: number]: string; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { readonly url: string; - clone(): Request; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; } -declare var Request: { - prototype: Request; - new(input: Request | string, init?: RequestInit): Request; +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; } -interface Response extends Object, Body { - readonly body: ReadableStream | null; - readonly headers: Headers; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly type: ResponseType; - readonly url: string; - clone(): Response; +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet; + readonly title: string; + readonly type: string; } -declare var Response: { - prototype: Response; - new(body?: any, init?: ResponseInit): Response; +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; } +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface StyleSheetPageList { + readonly length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} + +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9377,7 +9792,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -9401,7 +9816,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -9411,7 +9826,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -9421,7 +9836,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -9431,7 +9846,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -9441,7 +9856,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -9451,7 +9866,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -9461,7 +9876,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -9471,7 +9886,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -9481,7 +9896,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -9491,7 +9906,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -9501,7 +9916,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -9511,7 +9926,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -9521,7 +9936,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9534,7 +9949,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -9545,7 +9960,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -9574,7 +9989,7 @@ declare var SVGComponentTransferFunctionElement: { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} +}; interface SVGDefsElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9584,7 +9999,7 @@ interface SVGDefsElement extends SVGGraphicsElement { declare var SVGDefsElement: { prototype: SVGDefsElement; new(): SVGDefsElement; -} +}; interface SVGDescElement extends SVGElement { addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9594,7 +10009,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -9632,7 +10047,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -9648,7 +10063,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -9658,7 +10073,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9672,7 +10087,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9719,7 +10134,7 @@ declare var SVGFEBlendElement: { readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; -} +}; interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9742,7 +10157,7 @@ declare var SVGFEColorMatrixElement: { readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; -} +}; interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9753,7 +10168,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9784,7 +10199,7 @@ declare var SVGFECompositeElement: { readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; -} +}; interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly bias: SVGAnimatedNumber; @@ -9814,7 +10229,7 @@ declare var SVGFEConvolveMatrixElement: { readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; -} +}; interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly diffuseConstant: SVGAnimatedNumber; @@ -9829,7 +10244,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9854,7 +10269,7 @@ declare var SVGFEDisplacementMapElement: { readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; -} +}; interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; @@ -9866,7 +10281,7 @@ interface SVGFEDistantLightElement extends SVGElement { declare var SVGFEDistantLightElement: { prototype: SVGFEDistantLightElement; new(): SVGFEDistantLightElement; -} +}; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9876,7 +10291,7 @@ interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEFloodElement: { prototype: SVGFEFloodElement; new(): SVGFEFloodElement; -} +}; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9886,7 +10301,7 @@ interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncAElement: { prototype: SVGFEFuncAElement; new(): SVGFEFuncAElement; -} +}; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9896,7 +10311,7 @@ interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncBElement: { prototype: SVGFEFuncBElement; new(): SVGFEFuncBElement; -} +}; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9906,7 +10321,7 @@ interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncGElement: { prototype: SVGFEFuncGElement; new(): SVGFEFuncGElement; -} +}; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9916,7 +10331,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9930,7 +10345,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -9941,7 +10356,7 @@ interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEImageElement: { prototype: SVGFEImageElement; new(): SVGFEImageElement; -} +}; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9951,7 +10366,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -9962,7 +10377,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9982,7 +10397,7 @@ declare var SVGFEMorphologyElement: { readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; -} +}; interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly dx: SVGAnimatedNumber; @@ -9995,7 +10410,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -10008,7 +10423,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10024,7 +10439,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -10042,7 +10457,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10053,7 +10468,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -10081,7 +10496,7 @@ declare var SVGFETurbulenceElement: { readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; -} +}; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly filterResX: SVGAnimatedInteger; @@ -10100,7 +10515,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10114,7 +10529,7 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { declare var SVGForeignObjectElement: { prototype: SVGForeignObjectElement; new(): SVGForeignObjectElement; -} +}; interface SVGGElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10124,7 +10539,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -10145,7 +10560,7 @@ declare var SVGGradientElement: { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; -} +}; interface SVGGraphicsElement extends SVGElement, SVGTests { readonly farthestViewportElement: SVGElement; @@ -10162,7 +10577,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10177,7 +10592,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -10213,7 +10628,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -10229,21 +10644,7 @@ interface SVGLengthList { declare var SVGLengthList: { prototype: SVGLengthList; new(): SVGLengthList; -} - -interface SVGLineElement extends SVGGraphicsElement { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGLineElement: { - prototype: SVGLineElement; - new(): SVGLineElement; -} +}; interface SVGLinearGradientElement extends SVGGradientElement { readonly x1: SVGAnimatedLength; @@ -10257,8 +10658,22 @@ interface SVGLinearGradientElement extends SVGGradientElement { declare var SVGLinearGradientElement: { prototype: SVGLinearGradientElement; new(): SVGLinearGradientElement; +}; + +interface SVGLineElement extends SVGGraphicsElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +}; + interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -10269,12 +10684,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly refY: SVGAnimatedLength; setOrientToAngle(angle: SVGAngle): void; setOrientToAuto(): void; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10282,13 +10697,13 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { declare var SVGMarkerElement: { prototype: SVGMarkerElement; new(): SVGMarkerElement; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; -} + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; +}; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly height: SVGAnimatedLength; @@ -10304,7 +10719,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -10329,7 +10744,7 @@ interface SVGMatrix { declare var SVGMatrix: { prototype: SVGMatrix; new(): SVGMatrix; -} +}; interface SVGMetadataElement extends SVGElement { addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10339,7 +10754,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -10348,7 +10763,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -10364,7 +10779,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -10397,7 +10812,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -10447,7 +10862,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -10462,7 +10877,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -10477,7 +10892,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -10485,7 +10900,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -10499,7 +10914,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -10513,7 +10928,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -10525,7 +10940,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -10537,7 +10952,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -10549,7 +10964,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -10561,7 +10976,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -10571,7 +10986,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -10581,7 +10996,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -10591,7 +11006,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -10600,7 +11015,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -10609,7 +11024,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -10619,7 +11034,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -10628,7 +11043,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -10637,7 +11052,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -10653,7 +11068,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -10663,7 +11078,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -10673,7 +11088,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10690,7 +11105,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -10701,7 +11116,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -10717,7 +11132,7 @@ interface SVGPointList { declare var SVGPointList: { prototype: SVGPointList; new(): SVGPointList; -} +}; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10727,7 +11142,7 @@ interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolygonElement: { prototype: SVGPolygonElement; new(): SVGPolygonElement; -} +}; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10737,7 +11152,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -10775,7 +11190,7 @@ declare var SVGPreserveAspectRatio: { readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} +}; interface SVGRadialGradientElement extends SVGGradientElement { readonly cx: SVGAnimatedLength; @@ -10790,7 +11205,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -10802,7 +11217,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10818,8 +11233,60 @@ interface SVGRectElement extends SVGGraphicsElement { declare var SVGRectElement: { prototype: SVGRectElement; new(): SVGRectElement; +}; + +interface SVGScriptElement extends SVGElement, SVGURIReference { + type: string; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +}; + +interface SVGStopElement extends SVGElement { + readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +}; + +interface SVGStringList { + readonly numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +}; + +interface SVGStyleElement extends SVGElement { + disabled: boolean; + media: string; + title: string; + type: string; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +}; + interface SVGSVGElementEventMap extends SVGElementEventMap { "SVGAbort": Event; "SVGError": Event; @@ -10879,59 +11346,7 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB declare var SVGSVGElement: { prototype: SVGSVGElement; new(): SVGSVGElement; -} - -interface SVGScriptElement extends SVGElement, SVGURIReference { - type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGScriptElement: { - prototype: SVGScriptElement; - new(): SVGScriptElement; -} - -interface SVGStopElement extends SVGElement { - readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStopElement: { - prototype: SVGStopElement; - new(): SVGStopElement; -} - -interface SVGStringList { - readonly numberOfItems: number; - appendItem(newItem: string): string; - clear(): void; - getItem(index: number): string; - initialize(newItem: string): string; - insertItemBefore(newItem: string, index: number): string; - removeItem(index: number): string; - replaceItem(newItem: string, index: number): string; -} - -declare var SVGStringList: { - prototype: SVGStringList; - new(): SVGStringList; -} - -interface SVGStyleElement extends SVGElement { - disabled: boolean; - media: string; - title: string; - type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStyleElement: { - prototype: SVGStyleElement; - new(): SVGStyleElement; -} +}; interface SVGSwitchElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10941,7 +11356,7 @@ interface SVGSwitchElement extends SVGGraphicsElement { declare var SVGSwitchElement: { prototype: SVGSwitchElement; new(): SVGSwitchElement; -} +}; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10951,17 +11366,7 @@ interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { declare var SVGSymbolElement: { prototype: SVGSymbolElement; new(): SVGSymbolElement; -} - -interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -} +}; interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; @@ -10988,7 +11393,7 @@ declare var SVGTextContentElement: { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; -} +}; interface SVGTextElement extends SVGTextPositioningElement { addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10998,7 +11403,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -11023,7 +11428,7 @@ declare var SVGTextPathElement: { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; -} +}; interface SVGTextPositioningElement extends SVGTextContentElement { readonly dx: SVGAnimatedLengthList; @@ -11038,7 +11443,7 @@ interface SVGTextPositioningElement extends SVGTextContentElement { declare var SVGTextPositioningElement: { prototype: SVGTextPositioningElement; new(): SVGTextPositioningElement; -} +}; interface SVGTitleElement extends SVGElement { addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -11048,7 +11453,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -11079,7 +11484,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -11097,8 +11502,18 @@ interface SVGTransformList { declare var SVGTransformList: { prototype: SVGTransformList; new(): SVGTransformList; +}; + +interface SVGTSpanElement extends SVGTextPositioningElement { + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +}; + interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -11120,7 +11535,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -11131,7 +11546,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -11141,7 +11556,7 @@ declare var SVGZoomAndPan: { readonly SVG_ZOOMANDPAN_DISABLE: number; readonly SVG_ZOOMANDPAN_MAGNIFY: number; readonly SVG_ZOOMANDPAN_UNKNOWN: number; -} +}; interface SVGZoomEvent extends UIEvent { readonly newScale: number; @@ -11154,420 +11569,7 @@ interface SVGZoomEvent extends UIEvent { declare var SVGZoomEvent: { prototype: SVGZoomEvent; new(): SVGZoomEvent; -} - -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; -} - -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; -} - -interface ScopedCredentialInfo { - readonly credential: ScopedCredential; - readonly publicKey: CryptoKey; -} - -declare var ScopedCredentialInfo: { - prototype: ScopedCredentialInfo; - new(): ScopedCredentialInfo; -} - -interface ScreenEventMap { - "MSOrientationChange": Event; -} - -interface Screen extends EventTarget { - readonly availHeight: number; - readonly availWidth: number; - bufferDepth: number; - readonly colorDepth: number; - readonly deviceXDPI: number; - readonly deviceYDPI: number; - readonly fontSmoothingEnabled: boolean; - readonly height: number; - readonly logicalXDPI: number; - readonly logicalYDPI: number; - readonly msOrientation: string; - onmsorientationchange: (this: Screen, ev: Event) => any; - readonly pixelDepth: number; - readonly systemXDPI: number; - readonly systemYDPI: number; - readonly width: number; - msLockOrientation(orientations: string | string[]): boolean; - msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Screen: { - prototype: Screen; - new(): Screen; -} - -interface ScriptNotifyEvent extends Event { - readonly callingUri: string; - readonly value: string; -} - -declare var ScriptNotifyEvent: { - prototype: ScriptNotifyEvent; - new(): ScriptNotifyEvent; -} - -interface ScriptProcessorNodeEventMap { - "audioprocess": AudioProcessingEvent; -} - -interface ScriptProcessorNode extends AudioNode { - readonly bufferSize: number; - onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ScriptProcessorNode: { - prototype: ScriptProcessorNode; - new(): ScriptProcessorNode; -} - -interface Selection { - readonly anchorNode: Node; - readonly anchorOffset: number; - readonly baseNode: Node; - readonly baseOffset: number; - readonly extentNode: Node; - readonly extentOffset: number; - readonly focusNode: Node; - readonly focusOffset: number; - readonly isCollapsed: boolean; - readonly rangeCount: number; - readonly type: string; - addRange(range: Range): void; - collapse(parentNode: Node, offset: number): void; - collapseToEnd(): void; - collapseToStart(): void; - containsNode(node: Node, partlyContained: boolean): boolean; - deleteFromDocument(): void; - empty(): void; - extend(newNode: Node, offset: number): void; - getRangeAt(index: number): Range; - removeAllRanges(): void; - removeRange(range: Range): void; - selectAllChildren(parentNode: Node): void; - setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; - setPosition(parentNode: Node, offset: number): void; - toString(): string; -} - -declare var Selection: { - prototype: Selection; - new(): Selection; -} - -interface ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; -} - -interface ServiceWorker extends EventTarget, AbstractWorker { - onstatechange: (this: ServiceWorker, ev: Event) => any; - readonly scriptURL: USVString; - readonly state: ServiceWorkerState; - postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorker: { - prototype: ServiceWorker; - new(): ServiceWorker; -} - -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; -} - -interface ServiceWorkerContainer extends EventTarget { - readonly controller: ServiceWorker | null; - oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; - onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; - readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; - register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerContainer: { - prototype: ServiceWorkerContainer; - new(): ServiceWorkerContainer; -} - -interface ServiceWorkerMessageEvent extends Event { - readonly data: any; - readonly lastEventId: string; - readonly origin: string; - readonly ports: MessagePort[] | null; - readonly source: ServiceWorker | MessagePort | null; -} - -declare var ServiceWorkerMessageEvent: { - prototype: ServiceWorkerMessageEvent; - new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; -} - -interface ServiceWorkerRegistrationEventMap { - "updatefound": Event; -} - -interface ServiceWorkerRegistration extends EventTarget { - readonly active: ServiceWorker | null; - readonly installing: ServiceWorker | null; - onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; - readonly pushManager: PushManager; - readonly scope: USVString; - readonly sync: SyncManager; - readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; - showNotification(title: string, options?: NotificationOptions): Promise; - unregister(): Promise; - update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerRegistration: { - prototype: ServiceWorkerRegistration; - new(): ServiceWorkerRegistration; -} - -interface SourceBuffer extends EventTarget { - appendWindowEnd: number; - appendWindowStart: number; - readonly audioTracks: AudioTrackList; - readonly buffered: TimeRanges; - mode: AppendMode; - timestampOffset: number; - readonly updating: boolean; - readonly videoTracks: VideoTrackList; - abort(): void; - appendBuffer(data: ArrayBuffer | ArrayBufferView): void; - appendStream(stream: MSStream, maxSize?: number): void; - remove(start: number, end: number): void; -} - -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - -interface SourceBufferList extends EventTarget { - readonly length: number; - item(index: number): SourceBuffer; - [index: number]: SourceBuffer; -} - -declare var SourceBufferList: { - prototype: SourceBufferList; - new(): SourceBufferList; -} - -interface SpeechSynthesisEventMap { - "voiceschanged": Event; -} - -interface SpeechSynthesis extends EventTarget { - onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; - readonly paused: boolean; - readonly pending: boolean; - readonly speaking: boolean; - cancel(): void; - getVoices(): SpeechSynthesisVoice[]; - pause(): void; - resume(): void; - speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesis: { - prototype: SpeechSynthesis; - new(): SpeechSynthesis; -} - -interface SpeechSynthesisEvent extends Event { - readonly charIndex: number; - readonly elapsedTime: number; - readonly name: string; - readonly utterance: SpeechSynthesisUtterance | null; -} - -declare var SpeechSynthesisEvent: { - prototype: SpeechSynthesisEvent; - new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; -} - -interface SpeechSynthesisUtteranceEventMap { - "boundary": Event; - "end": Event; - "error": Event; - "mark": Event; - "pause": Event; - "resume": Event; - "start": Event; -} - -interface SpeechSynthesisUtterance extends EventTarget { - lang: string; - onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; - onend: (this: SpeechSynthesisUtterance, ev: Event) => any; - onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; - onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; - onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; - onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; - onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; - pitch: number; - rate: number; - text: string; - voice: SpeechSynthesisVoice; - volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesisUtterance: { - prototype: SpeechSynthesisUtterance; - new(text?: string): SpeechSynthesisUtterance; -} - -interface SpeechSynthesisVoice { - readonly default: boolean; - readonly lang: string; - readonly localService: boolean; - readonly name: string; - readonly voiceURI: string; -} - -declare var SpeechSynthesisVoice: { - prototype: SpeechSynthesisVoice; - new(): SpeechSynthesisVoice; -} - -interface StereoPannerNode extends AudioNode { - readonly pan: AudioParam; -} - -declare var StereoPannerNode: { - prototype: StereoPannerNode; - new(): StereoPannerNode; -} - -interface Storage { - readonly length: number; - clear(): void; - getItem(key: string): string | null; - key(index: number): string | null; - removeItem(key: string): void; - setItem(key: string, data: string): void; - [key: string]: any; - [index: number]: string; -} - -declare var Storage: { - prototype: Storage; - new(): Storage; -} - -interface StorageEvent extends Event { - readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; -} - -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; -} - -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; -} - -declare var StyleMedia: { - prototype: StyleMedia; - new(): StyleMedia; -} - -interface StyleSheet { - disabled: boolean; - readonly href: string; - readonly media: MediaList; - readonly ownerNode: Node; - readonly parentStyleSheet: StyleSheet; - readonly title: string; - readonly type: string; -} - -declare var StyleSheet: { - prototype: StyleSheet; - new(): StyleSheet; -} - -interface StyleSheetList { - readonly length: number; - item(index?: number): StyleSheet; - [index: number]: StyleSheet; -} - -declare var StyleSheetList: { - prototype: StyleSheetList; - new(): StyleSheetList; -} - -interface StyleSheetPageList { - readonly length: number; - item(index: number): CSSPageRule; - [index: number]: CSSPageRule; -} - -declare var StyleSheetPageList: { - prototype: StyleSheetPageList; - new(): StyleSheetPageList; -} - -interface SubtleCrypto { - decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; - encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - exportKey(format: "jwk", key: CryptoKey): PromiseLike; - exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; - unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; -} - -declare var SubtleCrypto: { - prototype: SubtleCrypto; - new(): SubtleCrypto; -} +}; interface SyncManager { getTags(): any; @@ -11577,7 +11579,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -11588,7 +11590,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -11620,7 +11622,7 @@ declare var TextEvent: { readonly DOM_INPUT_METHOD_SCRIPT: number; readonly DOM_INPUT_METHOD_UNKNOWN: number; readonly DOM_INPUT_METHOD_VOICE: number; -} +}; interface TextMetrics { readonly width: number; @@ -11629,7 +11631,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -11672,7 +11674,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -11696,7 +11698,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -11708,7 +11710,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -11726,7 +11728,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -11737,7 +11739,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -11753,7 +11755,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -11771,7 +11773,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -11782,7 +11784,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -11791,7 +11793,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -11802,7 +11804,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -11822,7 +11824,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -11833,8 +11835,17 @@ interface UIEvent extends Event { declare var UIEvent: { prototype: UIEvent; new(typeArg: string, eventInitDict?: UIEventInit): UIEvent; +}; + +interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { + readonly mediaType: string; } +declare var UnviewableContentIdentifiedEvent: { + prototype: UnviewableContentIdentifiedEvent; + new(): UnviewableContentIdentifiedEvent; +}; + interface URL { hash: string; host: string; @@ -11856,16 +11867,7 @@ declare var URL: { new(url: string, base?: string): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; -} - -interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { - readonly mediaType: string; -} - -declare var UnviewableContentIdentifiedEvent: { - prototype: UnviewableContentIdentifiedEvent; - new(): UnviewableContentIdentifiedEvent; -} +}; interface ValidityState { readonly badInput: boolean; @@ -11883,7 +11885,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -11896,7 +11898,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -11910,7 +11912,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -11934,45 +11936,7 @@ interface VideoTrackList extends EventTarget { declare var VideoTrackList: { prototype: VideoTrackList; new(): VideoTrackList; -} - -interface WEBGL_compressed_texture_s3tc { - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -declare var WEBGL_compressed_texture_s3tc: { - prototype: WEBGL_compressed_texture_s3tc; - new(): WEBGL_compressed_texture_s3tc; - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -interface WEBGL_debug_renderer_info { - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -declare var WEBGL_debug_renderer_info: { - prototype: WEBGL_debug_renderer_info; - new(): WEBGL_debug_renderer_info; - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -interface WEBGL_depth_texture { - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -declare var WEBGL_depth_texture: { - prototype: WEBGL_depth_texture; - new(): WEBGL_depth_texture; - readonly UNSIGNED_INT_24_8_WEBGL: number; -} +}; interface WaveShaperNode extends AudioNode { curve: Float32Array | null; @@ -11982,7 +11946,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -11992,7 +11956,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -12004,8 +11968,46 @@ interface WebAuthnAssertion { declare var WebAuthnAssertion: { prototype: WebAuthnAssertion; new(): WebAuthnAssertion; +}; + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; } +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; +}; + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +declare var WEBGL_debug_renderer_info: { + prototype: WEBGL_debug_renderer_info; + new(): WEBGL_debug_renderer_info; + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +}; + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +declare var WEBGL_depth_texture: { + prototype: WEBGL_depth_texture; + new(): WEBGL_depth_texture; + readonly UNSIGNED_INT_24_8_WEBGL: number; +}; + interface WebGLActiveInfo { readonly name: string; readonly size: number; @@ -12015,7 +12017,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -12023,7 +12025,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -12032,7 +12034,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -12040,7 +12042,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -12048,7 +12050,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -12056,7 +12058,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -12064,7 +12066,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -12325,13 +12327,13 @@ interface WebGLRenderingContext { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12356,9 +12358,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12388,18 +12390,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -12433,6 +12435,20 @@ interface WebGLRenderingContext { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -12465,23 +12481,9 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -12627,13 +12629,13 @@ declare var WebGLRenderingContext: { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12658,9 +12660,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12690,18 +12692,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -12735,6 +12737,20 @@ declare var WebGLRenderingContext: { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -12767,23 +12783,9 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -12807,7 +12809,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -12815,7 +12817,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -12826,7 +12828,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -12834,7 +12836,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -12842,7 +12844,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -12882,7 +12884,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -12891,7 +12893,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -12900,7 +12902,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -12913,7 +12915,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -12922,7 +12924,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -12932,7 +12934,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -12942,8 +12944,18 @@ interface WebKitPoint { declare var WebKitPoint: { prototype: WebKitPoint; new(x?: number, y?: number): WebKitPoint; +}; + +interface webkitRTCPeerConnection extends RTCPeerConnection { + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; +}; + interface WebSocketEventMap { "close": CloseEvent; "error": Event; @@ -12979,7 +12991,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -13002,7 +13014,7 @@ declare var WheelEvent: { readonly DOM_DELTA_LINE: number; readonly DOM_DELTA_PAGE: number; readonly DOM_DELTA_PIXEL: number; -} +}; interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -13030,6 +13042,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -13088,6 +13101,10 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "submit": Event; "suspend": Event; "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; "unload": Event; "volumechange": Event; "waiting": Event; @@ -13101,8 +13118,8 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly crypto: Crypto; defaultStatus: string; readonly devicePixelRatio: number; - readonly doNotTrack: string; readonly document: Document; + readonly doNotTrack: string; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -13225,9 +13242,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; + readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; - readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -13283,7 +13300,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -13300,7 +13317,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; -} +}; interface XMLDocument extends Document { addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; @@ -13310,7 +13327,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -13357,7 +13374,7 @@ declare var XMLHttpRequest: { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; -} +}; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; @@ -13367,7 +13384,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -13376,7 +13393,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -13387,7 +13404,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -13396,7 +13413,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -13405,7 +13422,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -13442,7 +13459,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -13458,17 +13475,7 @@ interface XSLTProcessor { declare var XSLTProcessor: { prototype: XSLTProcessor; new(): XSLTProcessor; -} - -interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var webkitRTCPeerConnection: { - prototype: webkitRTCPeerConnection; - new(configuration: RTCConfiguration): webkitRTCPeerConnection; -} +}; interface AbstractWorkerEventMap { "error": ErrorEvent; @@ -13505,6 +13512,81 @@ interface ChildNode { remove(): void; } +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface: "BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface: "ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface: "CloseEvent"): CloseEvent; + createEvent(eventInterface: "CompositionEvent"): CompositionEvent; + createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface: "DragEvent"): DragEvent; + createEvent(eventInterface: "ErrorEvent"): ErrorEvent; + createEvent(eventInterface: "Event"): Event; + createEvent(eventInterface: "Events"): Event; + createEvent(eventInterface: "FocusEvent"): FocusEvent; + createEvent(eventInterface: "FocusNavigationEvent"): FocusNavigationEvent; + createEvent(eventInterface: "GamepadEvent"): GamepadEvent; + createEvent(eventInterface: "HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface: "LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; + createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface: "MSManipulationEvent"): MSManipulationEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface: "MSSiteModeEvent"): MSSiteModeEvent; + createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface: "MediaStreamEvent"): MediaStreamEvent; + createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface: "MessageEvent"): MessageEvent; + createEvent(eventInterface: "MouseEvent"): MouseEvent; + createEvent(eventInterface: "MouseEvents"): MouseEvent; + createEvent(eventInterface: "MutationEvent"): MutationEvent; + createEvent(eventInterface: "MutationEvents"): MutationEvent; + createEvent(eventInterface: "NavigationCompletedEvent"): NavigationCompletedEvent; + createEvent(eventInterface: "NavigationEvent"): NavigationEvent; + createEvent(eventInterface: "NavigationEventWithReferrer"): NavigationEventWithReferrer; + createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface: "OverflowEvent"): OverflowEvent; + createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface: "PointerEvent"): PointerEvent; + createEvent(eventInterface: "PopStateEvent"): PopStateEvent; + createEvent(eventInterface: "ProgressEvent"): ProgressEvent; + createEvent(eventInterface: "RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface: "RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface: "RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface: "RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface: "RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; + createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface: "ScriptNotifyEvent"): ScriptNotifyEvent; + createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; + createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; + createEvent(eventInterface: "StorageEvent"): StorageEvent; + createEvent(eventInterface: "TextEvent"): TextEvent; + createEvent(eventInterface: "TouchEvent"): TouchEvent; + createEvent(eventInterface: "TrackEvent"): TrackEvent; + createEvent(eventInterface: "TransitionEvent"): TransitionEvent; + createEvent(eventInterface: "UIEvent"): UIEvent; + createEvent(eventInterface: "UIEvents"): UIEvent; + createEvent(eventInterface: "UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + interface DOML2DeprecatedColorProperty { color: string; } @@ -13513,81 +13595,6 @@ interface DOML2DeprecatedSizeProperty { size: number; } -interface DocumentEvent { - createEvent(eventInterface:"AnimationEvent"): AnimationEvent; - createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; - createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; - createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; - createEvent(eventInterface:"CloseEvent"): CloseEvent; - createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface:"CustomEvent"): CustomEvent; - createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; - createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; - createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; - createEvent(eventInterface:"DragEvent"): DragEvent; - createEvent(eventInterface:"ErrorEvent"): ErrorEvent; - createEvent(eventInterface:"Event"): Event; - createEvent(eventInterface:"Events"): Event; - createEvent(eventInterface:"FocusEvent"): FocusEvent; - createEvent(eventInterface:"FocusNavigationEvent"): FocusNavigationEvent; - createEvent(eventInterface:"GamepadEvent"): GamepadEvent; - createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; - createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; - createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; - createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; - createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; - createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; - createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; - createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; - createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; - createEvent(eventInterface:"MediaStreamEvent"): MediaStreamEvent; - createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; - createEvent(eventInterface:"MessageEvent"): MessageEvent; - createEvent(eventInterface:"MouseEvent"): MouseEvent; - createEvent(eventInterface:"MouseEvents"): MouseEvent; - createEvent(eventInterface:"MutationEvent"): MutationEvent; - createEvent(eventInterface:"MutationEvents"): MutationEvent; - createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; - createEvent(eventInterface:"NavigationEvent"): NavigationEvent; - createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; - createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; - createEvent(eventInterface:"OverflowEvent"): OverflowEvent; - createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; - createEvent(eventInterface:"PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; - createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; - createEvent(eventInterface:"PointerEvent"): PointerEvent; - createEvent(eventInterface:"PopStateEvent"): PopStateEvent; - createEvent(eventInterface:"ProgressEvent"): ProgressEvent; - createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; - createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; - createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; - createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; - createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; - createEvent(eventInterface:"RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; - createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; - createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; - createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; - createEvent(eventInterface:"ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; - createEvent(eventInterface:"SpeechSynthesisEvent"): SpeechSynthesisEvent; - createEvent(eventInterface:"StorageEvent"): StorageEvent; - createEvent(eventInterface:"TextEvent"): TextEvent; - createEvent(eventInterface:"TouchEvent"): TouchEvent; - createEvent(eventInterface:"TrackEvent"): TrackEvent; - createEvent(eventInterface:"TransitionEvent"): TransitionEvent; - createEvent(eventInterface:"UIEvent"): UIEvent; - createEvent(eventInterface:"UIEvents"): UIEvent; - createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; - createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; - createEvent(eventInterface:"WheelEvent"): WheelEvent; - createEvent(eventInterface: string): Event; -} - interface ElementTraversal { readonly childElementCount: number; readonly firstElementChild: Element | null; @@ -13632,16 +13639,16 @@ interface GlobalFetch { interface HTMLTableAlignment { /** - * Sets or retrieves a value that you can use to implement your own ch functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ ch: string; /** - * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ chOff: string; /** - * Sets or retrieves how text and other content are vertically aligned within the object that contains them. - */ + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ vAlign: string; } @@ -13866,38 +13873,38 @@ interface ImageBitmap { interface URLSearchParams { /** - * Appends a specified key/value pair as a new search parameter. - */ + * Appends a specified key/value pair as a new search parameter. + */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. - */ + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ delete(name: string): void; /** - * Returns the first value associated to the given search parameter. - */ + * Returns the first value associated to the given search parameter. + */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. - */ + * Returns all the values association with a given search parameter. + */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. - */ + * Returns a Boolean indicating if such a search parameter exists. + */ has(name: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. - */ + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ set(name: string, value: string): void; } declare var URLSearchParams: { prototype: URLSearchParams; /** - * Constructor returning a URLSearchParams object. - */ + * Constructor returning a URLSearchParams object. + */ new (init?: string | URLSearchParams): URLSearchParams; -} +}; interface NodeListOf extends NodeList { length: number; @@ -14145,7 +14152,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -14195,8 +14202,50 @@ interface TouchEventInit extends EventModifierInit { declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; + (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; +} +interface ForEachCallback { + (keyId: any, status: MediaKeyStatus): void; +} +interface FrameRequestCallback { + (time: number): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface IntersectionObserverCallback { + (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface MSLaunchUriCallback { + (): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} +interface NavigatorUserMediaErrorCallback { + (error: MediaStreamError): void; +} +interface NavigatorUserMediaSuccessCallback { + (stream: MediaStream): void; +} +interface NotificationPermissionCallback { + (permission: NotificationPermission): void; } interface PositionCallback { (position: Position): void; @@ -14204,59 +14253,17 @@ interface PositionCallback { interface PositionErrorCallback { (error: PositionError): void; } -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} -interface MSLaunchUriCallback { - (): void; -} -interface FrameRequestCallback { - (time: number): void; -} -interface MSUnsafeFunctionCallback { - (): any; -} -interface MSExecAtPriorityFunctionCallback { - (...args: any[]): any; -} -interface MutationCallback { - (mutations: MutationRecord[], observer: MutationObserver): void; -} -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface VoidFunction { - (): void; +interface RTCPeerConnectionErrorCallback { + (error: DOMError): void; } interface RTCSessionDescriptionCallback { (sdp: RTCSessionDescription): void; } -interface RTCPeerConnectionErrorCallback { - (error: DOMError): void; -} interface RTCStatsCallback { (report: RTCStatsReport): void; } -interface FunctionStringCallback { - (data: string): void; -} -interface NavigatorUserMediaSuccessCallback { - (stream: MediaStream): void; -} -interface NavigatorUserMediaErrorCallback { - (error: MediaStreamError): void; -} -interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; -} -interface NotificationPermissionCallback { - (permission: NotificationPermission): void; -} -interface IntersectionObserverCallback { - (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +interface VoidFunction { + (): void; } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; @@ -14344,48 +14351,27 @@ interface HTMLElementTagNameMap { "xmp": HTMLPreElement; } -interface ElementTagNameMap { - "a": HTMLAnchorElement; +interface ElementTagNameMap extends HTMLElementTagNameMap { "abbr": HTMLElement; "acronym": HTMLElement; "address": HTMLElement; - "applet": HTMLAppletElement; - "area": HTMLAreaElement; "article": HTMLElement; "aside": HTMLElement; - "audio": HTMLAudioElement; "b": HTMLElement; - "base": HTMLBaseElement; - "basefont": HTMLBaseFontElement; "bdo": HTMLElement; "big": HTMLElement; - "blockquote": HTMLQuoteElement; - "body": HTMLBodyElement; - "br": HTMLBRElement; - "button": HTMLButtonElement; - "canvas": HTMLCanvasElement; - "caption": HTMLTableCaptionElement; "center": HTMLElement; "circle": SVGCircleElement; "cite": HTMLElement; "clippath": SVGClipPathElement; "code": HTMLElement; - "col": HTMLTableColElement; - "colgroup": HTMLTableColElement; - "data": HTMLDataElement; - "datalist": HTMLDataListElement; "dd": HTMLElement; "defs": SVGDefsElement; - "del": HTMLModElement; "desc": SVGDescElement; "dfn": HTMLElement; - "dir": HTMLDirectoryElement; - "div": HTMLDivElement; - "dl": HTMLDListElement; "dt": HTMLElement; "ellipse": SVGEllipseElement; "em": HTMLElement; - "embed": HTMLEmbedElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -14410,307 +14396,67 @@ interface ElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "fieldset": HTMLFieldSetElement; "figcaption": HTMLElement; "figure": HTMLElement; "filter": SVGFilterElement; - "font": HTMLFontElement; "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; - "form": HTMLFormElement; - "frame": HTMLFrameElement; - "frameset": HTMLFrameSetElement; "g": SVGGElement; - "h1": HTMLHeadingElement; - "h2": HTMLHeadingElement; - "h3": HTMLHeadingElement; - "h4": HTMLHeadingElement; - "h5": HTMLHeadingElement; - "h6": HTMLHeadingElement; - "head": HTMLHeadElement; "header": HTMLElement; "hgroup": HTMLElement; - "hr": HTMLHRElement; - "html": HTMLHtmlElement; "i": HTMLElement; - "iframe": HTMLIFrameElement; "image": SVGImageElement; - "img": HTMLImageElement; - "input": HTMLInputElement; - "ins": HTMLModElement; - "isindex": HTMLUnknownElement; "kbd": HTMLElement; "keygen": HTMLElement; - "label": HTMLLabelElement; - "legend": HTMLLegendElement; - "li": HTMLLIElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "link": HTMLLinkElement; - "listing": HTMLPreElement; - "map": HTMLMapElement; "mark": HTMLElement; "marker": SVGMarkerElement; - "marquee": HTMLMarqueeElement; "mask": SVGMaskElement; - "menu": HTMLMenuElement; - "meta": HTMLMetaElement; "metadata": SVGMetadataElement; - "meter": HTMLMeterElement; "nav": HTMLElement; - "nextid": HTMLUnknownElement; "nobr": HTMLElement; "noframes": HTMLElement; "noscript": HTMLElement; - "object": HTMLObjectElement; - "ol": HTMLOListElement; - "optgroup": HTMLOptGroupElement; - "option": HTMLOptionElement; - "output": HTMLOutputElement; - "p": HTMLParagraphElement; - "param": HTMLParamElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "picture": HTMLPictureElement; "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; - "pre": HTMLPreElement; - "progress": HTMLProgressElement; - "q": HTMLQuoteElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; "rt": HTMLElement; "ruby": HTMLElement; "s": HTMLElement; "samp": HTMLElement; - "script": HTMLScriptElement; "section": HTMLElement; - "select": HTMLSelectElement; "small": HTMLElement; - "source": HTMLSourceElement; - "span": HTMLSpanElement; "stop": SVGStopElement; "strike": HTMLElement; "strong": HTMLElement; - "style": HTMLStyleElement; "sub": HTMLElement; "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; - "table": HTMLTableElement; - "tbody": HTMLTableSectionElement; - "td": HTMLTableDataCellElement; - "template": HTMLTemplateElement; "text": SVGTextElement; "textpath": SVGTextPathElement; - "textarea": HTMLTextAreaElement; - "tfoot": HTMLTableSectionElement; - "th": HTMLTableHeaderCellElement; - "thead": HTMLTableSectionElement; - "time": HTMLTimeElement; - "title": HTMLTitleElement; - "tr": HTMLTableRowElement; - "track": HTMLTrackElement; "tspan": SVGTSpanElement; "tt": HTMLElement; "u": HTMLElement; - "ul": HTMLUListElement; "use": SVGUseElement; "var": HTMLElement; - "video": HTMLVideoElement; "view": SVGViewElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; - "xmp": HTMLPreElement; } -interface ElementListTagNameMap { - "a": NodeListOf; - "abbr": NodeListOf; - "acronym": NodeListOf; - "address": NodeListOf; - "applet": NodeListOf; - "area": NodeListOf; - "article": NodeListOf; - "aside": NodeListOf; - "audio": NodeListOf; - "b": NodeListOf; - "base": NodeListOf; - "basefont": NodeListOf; - "bdo": NodeListOf; - "big": NodeListOf; - "blockquote": NodeListOf; - "body": NodeListOf; - "br": NodeListOf; - "button": NodeListOf; - "canvas": NodeListOf; - "caption": NodeListOf; - "center": NodeListOf; - "circle": NodeListOf; - "cite": NodeListOf; - "clippath": NodeListOf; - "code": NodeListOf; - "col": NodeListOf; - "colgroup": NodeListOf; - "data": NodeListOf; - "datalist": NodeListOf; - "dd": NodeListOf; - "defs": NodeListOf; - "del": NodeListOf; - "desc": NodeListOf; - "dfn": NodeListOf; - "dir": NodeListOf; - "div": NodeListOf; - "dl": NodeListOf; - "dt": NodeListOf; - "ellipse": NodeListOf; - "em": NodeListOf; - "embed": NodeListOf; - "feblend": NodeListOf; - "fecolormatrix": NodeListOf; - "fecomponenttransfer": NodeListOf; - "fecomposite": NodeListOf; - "feconvolvematrix": NodeListOf; - "fediffuselighting": NodeListOf; - "fedisplacementmap": NodeListOf; - "fedistantlight": NodeListOf; - "feflood": NodeListOf; - "fefunca": NodeListOf; - "fefuncb": NodeListOf; - "fefuncg": NodeListOf; - "fefuncr": NodeListOf; - "fegaussianblur": NodeListOf; - "feimage": NodeListOf; - "femerge": NodeListOf; - "femergenode": NodeListOf; - "femorphology": NodeListOf; - "feoffset": NodeListOf; - "fepointlight": NodeListOf; - "fespecularlighting": NodeListOf; - "fespotlight": NodeListOf; - "fetile": NodeListOf; - "feturbulence": NodeListOf; - "fieldset": NodeListOf; - "figcaption": NodeListOf; - "figure": NodeListOf; - "filter": NodeListOf; - "font": NodeListOf; - "footer": NodeListOf; - "foreignobject": NodeListOf; - "form": NodeListOf; - "frame": NodeListOf; - "frameset": NodeListOf; - "g": NodeListOf; - "h1": NodeListOf; - "h2": NodeListOf; - "h3": NodeListOf; - "h4": NodeListOf; - "h5": NodeListOf; - "h6": NodeListOf; - "head": NodeListOf; - "header": NodeListOf; - "hgroup": NodeListOf; - "hr": NodeListOf; - "html": NodeListOf; - "i": NodeListOf; - "iframe": NodeListOf; - "image": NodeListOf; - "img": NodeListOf; - "input": NodeListOf; - "ins": NodeListOf; - "isindex": NodeListOf; - "kbd": NodeListOf; - "keygen": NodeListOf; - "label": NodeListOf; - "legend": NodeListOf; - "li": NodeListOf; - "line": NodeListOf; - "lineargradient": NodeListOf; - "link": NodeListOf; - "listing": NodeListOf; - "map": NodeListOf; - "mark": NodeListOf; - "marker": NodeListOf; - "marquee": NodeListOf; - "mask": NodeListOf; - "menu": NodeListOf; - "meta": NodeListOf; - "metadata": NodeListOf; - "meter": NodeListOf; - "nav": NodeListOf; - "nextid": NodeListOf; - "nobr": NodeListOf; - "noframes": NodeListOf; - "noscript": NodeListOf; - "object": NodeListOf; - "ol": NodeListOf; - "optgroup": NodeListOf; - "option": NodeListOf; - "output": NodeListOf; - "p": NodeListOf; - "param": NodeListOf; - "path": NodeListOf; - "pattern": NodeListOf; - "picture": NodeListOf; - "plaintext": NodeListOf; - "polygon": NodeListOf; - "polyline": NodeListOf; - "pre": NodeListOf; - "progress": NodeListOf; - "q": NodeListOf; - "radialgradient": NodeListOf; - "rect": NodeListOf; - "rt": NodeListOf; - "ruby": NodeListOf; - "s": NodeListOf; - "samp": NodeListOf; - "script": NodeListOf; - "section": NodeListOf; - "select": NodeListOf; - "small": NodeListOf; - "source": NodeListOf; - "span": NodeListOf; - "stop": NodeListOf; - "strike": NodeListOf; - "strong": NodeListOf; - "style": NodeListOf; - "sub": NodeListOf; - "sup": NodeListOf; - "svg": NodeListOf; - "switch": NodeListOf; - "symbol": NodeListOf; - "table": NodeListOf; - "tbody": NodeListOf; - "td": NodeListOf; - "template": NodeListOf; - "text": NodeListOf; - "textpath": NodeListOf; - "textarea": NodeListOf; - "tfoot": NodeListOf; - "th": NodeListOf; - "thead": NodeListOf; - "time": NodeListOf; - "title": NodeListOf; - "tr": NodeListOf; - "track": NodeListOf; - "tspan": NodeListOf; - "tt": NodeListOf; - "u": NodeListOf; - "ul": NodeListOf; - "use": NodeListOf; - "var": NodeListOf; - "video": NodeListOf; - "view": NodeListOf; - "wbr": NodeListOf; - "x-ms-webview": NodeListOf; - "xmp": NodeListOf; -} +type ElementListTagNameMap = { + [key in keyof ElementTagNameMap]: NodeListOf +}; -declare var Audio: {new(src?: string): HTMLAudioElement; }; -declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; -declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; +declare var Audio: { new(src?: string): HTMLAudioElement; }; +declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; +declare var Option: { new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; @@ -14718,8 +14464,8 @@ declare var closed: boolean; declare var crypto: Crypto; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var doNotTrack: string; declare var document: Document; +declare var doNotTrack: string; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -14842,9 +14588,9 @@ declare var screenLeft: number; declare var screenTop: number; declare var screenX: number; declare var screenY: number; +declare var scrollbars: BarProp; declare var scrollX: number; declare var scrollY: number; -declare var scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -14963,6 +14709,7 @@ type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; +type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; @@ -14976,6 +14723,12 @@ type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; type ListeningState = "inactive" | "active" | "disambiguation"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaStreamTrackState = "live" | "ended"; type MSCredentialType = "FIDO_2_0"; type MSIceAddrType = "os" | "stun" | "turn" | "peer-derived"; type MSIceType = "failed" | "direct" | "relay"; @@ -14983,12 +14736,6 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; -type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; -type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; -type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; -type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; -type MediaKeysRequirement = "required" | "optional" | "not-allowed"; -type MediaStreamTrackState = "live" | "ended"; type NavigationReason = "up" | "down" | "left" | "right"; type NavigationType = "navigate" | "reload" | "back_forward" | "prerender"; type NotificationDirection = "auto" | "ltr" | "rtl"; @@ -15000,6 +14747,14 @@ type PaymentComplete = "success" | "fail" | ""; type PaymentShippingType = "shipping" | "delivery" | "pickup"; type PushEncryptionKeyName = "p256dh" | "auth"; type PushPermissionState = "granted" | "denied" | "prompt"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestRedirect = "follow" | "error" | "manual"; +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type RTCBundlePolicy = "balanced" | "max-compat" | "max-bundle"; type RTCDegradationPreference = "maintain-framerate" | "maintain-resolution" | "balanced"; type RTCDtlsRole = "auto" | "client" | "server"; @@ -15007,9 +14762,9 @@ type RTCDtlsTransportState = "new" | "connecting" | "connected" | "closed"; type RTCIceCandidateType = "host" | "srflx" | "prflx" | "relay"; type RTCIceComponent = "RTP" | "RTCP"; type RTCIceConnectionState = "new" | "checking" | "connected" | "completed" | "failed" | "disconnected" | "closed"; -type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceGathererState = "new" | "gathering" | "complete"; type RTCIceGatheringState = "new" | "gathering" | "complete"; +type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceProtocol = "udp" | "tcp"; type RTCIceRole = "controlling" | "controlled"; type RTCIceTcpCandidateType = "active" | "passive" | "so"; @@ -15020,14 +14775,6 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " type RTCStatsIceCandidatePairState = "frozen" | "waiting" | "inprogress" | "failed" | "succeeded" | "cancelled"; type RTCStatsIceCandidateType = "host" | "serverreflexive" | "peerreflexive" | "relayed"; type RTCStatsType = "inboundrtp" | "outboundrtp" | "session" | "datachannel" | "track" | "transport" | "candidatepair" | "localcandidate" | "remotecandidate"; -type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; -type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; -type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; -type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; -type RequestRedirect = "follow" | "error" | "manual"; -type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; type Transport = "usb" | "nfc" | "ble"; diff --git a/src/lib/es2015.proxy.d.ts b/src/lib/es2015.proxy.d.ts index c1b7805bbcf..50671aedcce 100644 --- a/src/lib/es2015.proxy.d.ts +++ b/src/lib/es2015.proxy.d.ts @@ -3,7 +3,7 @@ interface ProxyHandler { setPrototypeOf? (target: T, v: any): boolean; isExtensible? (target: T): boolean; preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; has? (target: T, p: PropertyKey): boolean; get? (target: T, p: PropertyKey, receiver: any): any; set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; diff --git a/src/lib/es2017.d.ts b/src/lib/es2017.d.ts index 7b8c7cbb7d5..80282355a45 100644 --- a/src/lib/es2017.d.ts +++ b/src/lib/es2017.d.ts @@ -1,4 +1,5 @@ /// /// /// -/// \ No newline at end of file +/// +/// diff --git a/src/lib/es2017.intl.d.ts b/src/lib/es2017.intl.d.ts new file mode 100644 index 00000000000..b8783530190 --- /dev/null +++ b/src/lib/es2017.intl.d.ts @@ -0,0 +1,10 @@ +type DateTimeFormatPartTypes = "day" | "dayPeriod" | "era" | "hour" | "literal" | "minute" | "month" | "second" | "timeZoneName" | "weekday" | "year"; + +interface DateTimeFormatPart { + type: DateTimeFormatPartTypes; + value: string; +} + +interface DateTimeFormat { + formatToParts(date?: Date | number): DateTimeFormatPart[]; +} diff --git a/src/lib/es2017.sharedmemory.d.ts b/src/lib/es2017.sharedmemory.d.ts index e18390a5591..b9a9b0f7e10 100644 --- a/src/lib/es2017.sharedmemory.d.ts +++ b/src/lib/es2017.sharedmemory.d.ts @@ -23,5 +23,96 @@ interface SharedArrayBufferConstructor { readonly prototype: SharedArrayBuffer; new (byteLength: number): SharedArrayBuffer; } +declare var SharedArrayBuffer: SharedArrayBufferConstructor; -declare var SharedArrayBuffer: SharedArrayBufferConstructor; \ No newline at end of file +interface ArrayBufferTypes { + SharedArrayBuffer: SharedArrayBuffer; +} + +interface Atomics { + /** + * Adds a value to the value at the given position in the array, returning the original value. + * Until this atomic operation completes, any other read or write operation against the array + * will block. + */ + add(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Stores the bitwise AND of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or + * write operation against the array will block. + */ + and(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Replaces the value at the given position in the array if the original value equals the given + * expected value, returning the original value. Until this atomic operation completes, any + * other read or write operation against the array will block. + */ + compareExchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, expectedValue: number, replacementValue: number): number; + + /** + * Replaces the value at the given position in the array, returning the original value. Until + * this atomic operation completes, any other read or write operation against the array will + * block. + */ + exchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Returns a value indicating whether high-performance algorithms can use atomic operations + * (`true`) or must use locks (`false`) for the given number of bytes-per-element of a typed + * array. + */ + isLockFree(size: number): boolean; + + /** + * Returns the value at the given position in the array. Until this atomic operation completes, + * any other read or write operation against the array will block. + */ + load(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number): number; + + /** + * Stores the bitwise OR of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or write + * operation against the array will block. + */ + or(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Stores a value at the given position in the array, returning the new value. Until this + * atomic operation completes, any other read or write operation against the array will block. + */ + store(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Subtracts a value from the value at the given position in the array, returning the original + * value. Until this atomic operation completes, any other read or write operation against the + * array will block. + */ + sub(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * If the value at the given position in the array is equal to the provided value, the current + * agent is put to sleep causing execution to suspend until the timeout expires (returning + * `"timed-out"`) or until the agent is awoken (returning `"ok"`); otherwise, returns + * `"not-equal"`. + */ + wait(typedArray: Int32Array, index: number, value: number, timeout?: number): "ok" | "not-equal" | "timed-out"; + + /** + * Wakes up sleeping agents that are waiting on the given index of the array, returning the + * number of agents that were awoken. + */ + wake(typedArray: Int32Array, index: number, count: number): number; + + /** + * Stores the bitwise XOR of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or write + * operation against the array will block. + */ + xor(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + readonly [Symbol.toStringTag]: "Atomics"; +} + +declare var Atomics: Atomics; \ No newline at end of file diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index 23805495b69..3a85f4ddad9 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -1386,6 +1386,14 @@ interface ArrayBuffer { slice(begin: number, end?: number): ArrayBuffer; } +/** + * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. + */ +interface ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} +type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; + interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; @@ -1397,7 +1405,7 @@ interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1539,7 +1547,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; + new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1556,7 +1564,7 @@ interface Int8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1799,7 +1807,7 @@ interface Int8ArrayConstructor { readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1840,7 +1848,7 @@ interface Uint8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2084,7 +2092,7 @@ interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2125,7 +2133,7 @@ interface Uint8ClampedArray { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2369,7 +2377,7 @@ interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2409,7 +2417,7 @@ interface Int16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2653,7 +2661,7 @@ interface Int16ArrayConstructor { readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2694,7 +2702,7 @@ interface Uint16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2938,7 +2946,7 @@ interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2978,7 +2986,7 @@ interface Int32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3222,7 +3230,7 @@ interface Int32ArrayConstructor { readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3262,7 +3270,7 @@ interface Uint32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3506,7 +3514,7 @@ interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3546,7 +3554,7 @@ interface Float32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3790,7 +3798,7 @@ interface Float32ArrayConstructor { readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3831,7 +3839,7 @@ interface Float64Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -4075,7 +4083,7 @@ interface Float64ArrayConstructor { readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index 62d6d2d67a7..ba358d6402b 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -1,6 +1,6 @@ ///////////////////////////// -/// IE Worker APIs +/// Worker APIs ///////////////////////////// interface Algorithm { @@ -8,16 +8,16 @@ interface Algorithm { } interface CacheQueryOptions { - ignoreSearch?: boolean; - ignoreMethod?: boolean; - ignoreVary?: boolean; cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; } interface CloseEventInit extends EventInit { - wasClean?: boolean; code?: number; reason?: string; + wasClean?: boolean; } interface EventInit { @@ -49,16 +49,16 @@ interface MessageEventInit extends EventInit { channel?: string; data?: any; origin?: string; - source?: any; ports?: MessagePort[]; + source?: any; } interface NotificationOptions { - dir?: NotificationDirection; - lang?: string; body?: string; - tag?: string; + dir?: NotificationDirection; icon?: string; + lang?: string; + tag?: string; } interface ObjectURLOptions { @@ -66,29 +66,29 @@ interface ObjectURLOptions { } interface PushSubscriptionOptionsInit { - userVisibleOnly?: boolean; applicationServerKey?: any; + userVisibleOnly?: boolean; } interface RequestInit { - method?: string; - headers?: any; body?: any; - referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode?: RequestMode; - credentials?: RequestCredentials; cache?: RequestCache; - redirect?: RequestRedirect; + credentials?: RequestCredentials; + headers?: any; integrity?: string; keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; window?: any; } interface ResponseInit { + headers?: any; status?: number; statusText?: string; - headers?: any; } interface ClientQueryOptions { @@ -156,7 +156,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface Blob { readonly size: number; @@ -169,7 +169,7 @@ interface Blob { declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; -} +}; interface Cache { add(request: RequestInfo): Promise; @@ -184,7 +184,7 @@ interface Cache { declare var Cache: { prototype: Cache; new(): Cache; -} +}; interface CacheStorage { delete(cacheName: string): Promise; @@ -197,7 +197,7 @@ interface CacheStorage { declare var CacheStorage: { prototype: CacheStorage; new(): CacheStorage; -} +}; interface CloseEvent extends Event { readonly code: number; @@ -209,7 +209,7 @@ interface CloseEvent extends Event { declare var CloseEvent: { prototype: CloseEvent; new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; -} +}; interface Console { assert(test?: boolean, message?: string, ...optionalParams: any[]): void; @@ -220,8 +220,8 @@ interface Console { dirxml(value: any): void; error(message?: any, ...optionalParams: any[]): void; exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; groupEnd(): void; info(message?: any, ...optionalParams: any[]): void; log(message?: any, ...optionalParams: any[]): void; @@ -239,7 +239,7 @@ interface Console { declare var Console: { prototype: Console; new(): Console; -} +}; interface Coordinates { readonly accuracy: number; @@ -254,7 +254,7 @@ interface Coordinates { declare var Coordinates: { prototype: Coordinates; new(): Coordinates; -} +}; interface CryptoKey { readonly algorithm: KeyAlgorithm; @@ -266,7 +266,7 @@ interface CryptoKey { declare var CryptoKey: { prototype: CryptoKey; new(): CryptoKey; -} +}; interface DOMError { readonly name: string; @@ -276,7 +276,7 @@ interface DOMError { declare var DOMError: { prototype: DOMError; new(): DOMError; -} +}; interface DOMException { readonly code: number; @@ -296,10 +296,10 @@ interface DOMException { readonly INVALID_STATE_ERR: number; readonly NAMESPACE_ERR: number; readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; readonly NO_DATA_ALLOWED_ERR: number; readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; readonly PARSE_ERR: number; readonly QUOTA_EXCEEDED_ERR: number; readonly SECURITY_ERR: number; @@ -328,10 +328,10 @@ declare var DOMException: { readonly INVALID_STATE_ERR: number; readonly NAMESPACE_ERR: number; readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; readonly NO_DATA_ALLOWED_ERR: number; readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; readonly PARSE_ERR: number; readonly QUOTA_EXCEEDED_ERR: number; readonly SECURITY_ERR: number; @@ -342,7 +342,7 @@ declare var DOMException: { readonly URL_MISMATCH_ERR: number; readonly VALIDATION_ERR: number; readonly WRONG_DOCUMENT_ERR: number; -} +}; interface DOMStringList { readonly length: number; @@ -354,7 +354,7 @@ interface DOMStringList { declare var DOMStringList: { prototype: DOMStringList; new(): DOMStringList; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -368,12 +368,12 @@ interface ErrorEvent extends Event { declare var ErrorEvent: { prototype: ErrorEvent; new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent; -} +}; interface Event { readonly bubbles: boolean; - cancelBubble: boolean; readonly cancelable: boolean; + cancelBubble: boolean; readonly currentTarget: EventTarget; readonly defaultPrevented: boolean; readonly eventPhase: number; @@ -400,7 +400,7 @@ declare var Event: { readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; -} +}; interface EventTarget { addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -411,7 +411,7 @@ interface EventTarget { declare var EventTarget: { prototype: EventTarget; new(): EventTarget; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -422,7 +422,7 @@ interface File extends Blob { declare var File: { prototype: File; new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} +}; interface FileList { readonly length: number; @@ -433,7 +433,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -448,8 +448,17 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; +}; + +interface FormData { + append(name: string, value: string | Blob, fileName?: string): void; } +declare var FormData: { + prototype: FormData; + new(): FormData; +}; + interface Headers { append(name: string, value: string): void; delete(name: string): void; @@ -462,7 +471,7 @@ interface Headers { declare var Headers: { prototype: Headers; new(init?: any): Headers; -} +}; interface IDBCursor { readonly direction: IDBCursorDirection; @@ -486,7 +495,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -495,7 +504,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -512,7 +521,7 @@ interface IDBDatabase extends EventTarget { close(): void; createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -521,7 +530,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -532,7 +541,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -543,14 +552,14 @@ interface IDBIndex { count(key?: IDBKeyRange | IDBValidKey): IDBRequest; get(key: IDBKeyRange | IDBValidKey): IDBRequest; getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { prototype: IDBIndex; new(): IDBIndex; -} +}; interface IDBKeyRange { readonly lower: any; @@ -566,7 +575,7 @@ declare var IDBKeyRange: { lowerBound(lower: any, open?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; upperBound(upper: any, open?: boolean): IDBKeyRange; -} +}; interface IDBObjectStore { readonly indexNames: DOMStringList; @@ -582,14 +591,14 @@ interface IDBObjectStore { deleteIndex(indexName: string): void; get(key: any): IDBRequest; index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; new(): IDBObjectStore; -} +}; interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { "blocked": Event; @@ -606,7 +615,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -614,7 +623,7 @@ interface IDBRequestEventMap { } interface IDBRequest extends EventTarget { - readonly error: DOMError; + readonly error: DOMException; onerror: (this: IDBRequest, ev: Event) => any; onsuccess: (this: IDBRequest, ev: Event) => any; readonly readyState: IDBRequestReadyState; @@ -628,7 +637,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -638,7 +647,7 @@ interface IDBTransactionEventMap { interface IDBTransaction extends EventTarget { readonly db: IDBDatabase; - readonly error: DOMError; + readonly error: DOMException; readonly mode: IDBTransactionMode; onabort: (this: IDBTransaction, ev: Event) => any; oncomplete: (this: IDBTransaction, ev: Event) => any; @@ -658,7 +667,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -668,7 +677,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -680,7 +689,7 @@ declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} +}; interface MessageChannel { readonly port1: MessagePort; @@ -690,7 +699,7 @@ interface MessageChannel { declare var MessageChannel: { prototype: MessageChannel; new(): MessageChannel; -} +}; interface MessageEvent extends Event { readonly data: any; @@ -703,7 +712,7 @@ interface MessageEvent extends Event { declare var MessageEvent: { prototype: MessageEvent; new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} +}; interface MessagePortEventMap { "message": MessageEvent; @@ -721,7 +730,7 @@ interface MessagePort extends EventTarget { declare var MessagePort: { prototype: MessagePort; new(): MessagePort; -} +}; interface NotificationEventMap { "click": Event; @@ -751,7 +760,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface Performance { readonly navigation: PerformanceNavigation; @@ -774,7 +783,7 @@ interface Performance { declare var Performance: { prototype: Performance; new(): Performance; -} +}; interface PerformanceNavigation { readonly redirectCount: number; @@ -793,18 +802,18 @@ declare var PerformanceNavigation: { readonly TYPE_NAVIGATE: number; readonly TYPE_RELOAD: number; readonly TYPE_RESERVED: number; -} +}; interface PerformanceTiming { readonly connectEnd: number; readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; readonly domComplete: number; readonly domContentLoadedEventEnd: number; readonly domContentLoadedEventStart: number; readonly domInteractive: number; readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; @@ -824,7 +833,7 @@ interface PerformanceTiming { declare var PerformanceTiming: { prototype: PerformanceTiming; new(): PerformanceTiming; -} +}; interface Position { readonly coords: Coordinates; @@ -834,7 +843,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -851,7 +860,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -863,7 +872,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -874,7 +883,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -887,7 +896,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -897,7 +906,7 @@ interface PushSubscriptionOptions { declare var PushSubscriptionOptions: { prototype: PushSubscriptionOptions; new(): PushSubscriptionOptions; -} +}; interface ReadableStream { readonly locked: boolean; @@ -908,7 +917,7 @@ interface ReadableStream { declare var ReadableStream: { prototype: ReadableStream; new(): ReadableStream; -} +}; interface ReadableStreamReader { cancel(): Promise; @@ -919,7 +928,7 @@ interface ReadableStreamReader { declare var ReadableStreamReader: { prototype: ReadableStreamReader; new(): ReadableStreamReader; -} +}; interface Request extends Object, Body { readonly cache: RequestCache; @@ -941,7 +950,7 @@ interface Request extends Object, Body { declare var Request: { prototype: Request; new(input: Request | string, init?: RequestInit): Request; -} +}; interface Response extends Object, Body { readonly body: ReadableStream | null; @@ -957,7 +966,9 @@ interface Response extends Object, Body { declare var Response: { prototype: Response; new(body?: any, init?: ResponseInit): Response; -} + error: () => Response; + redirect: (url: string, status?: number) => Response; +}; interface ServiceWorkerEventMap extends AbstractWorkerEventMap { "statechange": Event; @@ -975,7 +986,7 @@ interface ServiceWorker extends EventTarget, AbstractWorker { declare var ServiceWorker: { prototype: ServiceWorker; new(): ServiceWorker; -} +}; interface ServiceWorkerRegistrationEventMap { "updatefound": Event; @@ -1000,7 +1011,7 @@ interface ServiceWorkerRegistration extends EventTarget { declare var ServiceWorkerRegistration: { prototype: ServiceWorkerRegistration; new(): ServiceWorkerRegistration; -} +}; interface SyncManager { getTags(): any; @@ -1010,7 +1021,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface URL { hash: string; @@ -1033,7 +1044,7 @@ declare var URL: { new(url: string, base?: string): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; -} +}; interface WebSocketEventMap { "close": CloseEvent; @@ -1070,7 +1081,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -1087,7 +1098,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -1133,7 +1144,7 @@ declare var XMLHttpRequest: { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; -} +}; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; @@ -1143,7 +1154,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface AbstractWorkerEventMap { "error": ErrorEvent; @@ -1258,7 +1269,7 @@ interface Client { declare var Client: { prototype: Client; new(): Client; -} +}; interface Clients { claim(): Promise; @@ -1270,7 +1281,7 @@ interface Clients { declare var Clients: { prototype: Clients; new(): Clients; -} +}; interface DedicatedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { "message": MessageEvent; @@ -1287,7 +1298,7 @@ interface DedicatedWorkerGlobalScope extends WorkerGlobalScope { declare var DedicatedWorkerGlobalScope: { prototype: DedicatedWorkerGlobalScope; new(): DedicatedWorkerGlobalScope; -} +}; interface ExtendableEvent extends Event { waitUntil(f: Promise): void; @@ -1296,7 +1307,7 @@ interface ExtendableEvent extends Event { declare var ExtendableEvent: { prototype: ExtendableEvent; new(type: string, eventInitDict?: ExtendableEventInit): ExtendableEvent; -} +}; interface ExtendableMessageEvent extends ExtendableEvent { readonly data: any; @@ -1309,7 +1320,7 @@ interface ExtendableMessageEvent extends ExtendableEvent { declare var ExtendableMessageEvent: { prototype: ExtendableMessageEvent; new(type: string, eventInitDict?: ExtendableMessageEventInit): ExtendableMessageEvent; -} +}; interface FetchEvent extends ExtendableEvent { readonly clientId: string | null; @@ -1321,7 +1332,7 @@ interface FetchEvent extends ExtendableEvent { declare var FetchEvent: { prototype: FetchEvent; new(type: string, eventInitDict: FetchEventInit): FetchEvent; -} +}; interface FileReaderSync { readAsArrayBuffer(blob: Blob): any; @@ -1333,7 +1344,7 @@ interface FileReaderSync { declare var FileReaderSync: { prototype: FileReaderSync; new(): FileReaderSync; -} +}; interface NotificationEvent extends ExtendableEvent { readonly action: string; @@ -1343,7 +1354,7 @@ interface NotificationEvent extends ExtendableEvent { declare var NotificationEvent: { prototype: NotificationEvent; new(type: string, eventInitDict: NotificationEventInit): NotificationEvent; -} +}; interface PushEvent extends ExtendableEvent { readonly data: PushMessageData | null; @@ -1352,7 +1363,7 @@ interface PushEvent extends ExtendableEvent { declare var PushEvent: { prototype: PushEvent; new(type: string, eventInitDict?: PushEventInit): PushEvent; -} +}; interface PushMessageData { arrayBuffer(): ArrayBuffer; @@ -1364,7 +1375,7 @@ interface PushMessageData { declare var PushMessageData: { prototype: PushMessageData; new(): PushMessageData; -} +}; interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { "activate": ExtendableEvent; @@ -1398,7 +1409,7 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { declare var ServiceWorkerGlobalScope: { prototype: ServiceWorkerGlobalScope; new(): ServiceWorkerGlobalScope; -} +}; interface SyncEvent extends ExtendableEvent { readonly lastChance: boolean; @@ -1408,7 +1419,7 @@ interface SyncEvent extends ExtendableEvent { declare var SyncEvent: { prototype: SyncEvent; new(type: string, init: SyncEventInit): SyncEvent; -} +}; interface WindowClient extends Client { readonly focused: boolean; @@ -1420,7 +1431,7 @@ interface WindowClient extends Client { declare var WindowClient: { prototype: WindowClient; new(): WindowClient; -} +}; interface WorkerGlobalScopeEventMap { "error": ErrorEvent; @@ -1443,7 +1454,7 @@ interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, Glo declare var WorkerGlobalScope: { prototype: WorkerGlobalScope; new(): WorkerGlobalScope; -} +}; interface WorkerLocation { readonly hash: string; @@ -1461,7 +1472,7 @@ interface WorkerLocation { declare var WorkerLocation: { prototype: WorkerLocation; new(): WorkerLocation; -} +}; interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, NavigatorBeacon, NavigatorConcurrentHardware { readonly hardwareConcurrency: number; @@ -1470,7 +1481,7 @@ interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, Navigato declare var WorkerNavigator: { prototype: WorkerNavigator; new(): WorkerNavigator; -} +}; interface WorkerUtils extends Object, WindowBase64 { readonly indexedDB: IDBFactory; @@ -1513,38 +1524,38 @@ interface ImageBitmap { interface URLSearchParams { /** - * Appends a specified key/value pair as a new search parameter. - */ + * Appends a specified key/value pair as a new search parameter. + */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. - */ + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ delete(name: string): void; /** - * Returns the first value associated to the given search parameter. - */ + * Returns the first value associated to the given search parameter. + */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. - */ + * Returns all the values association with a given search parameter. + */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. - */ + * Returns a Boolean indicating if such a search parameter exists. + */ has(name: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. - */ + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ set(name: string, value: string): void; } declare var URLSearchParams: { prototype: URLSearchParams; /** - * Constructor returning a URLSearchParams object. - */ + * Constructor returning a URLSearchParams object. + */ new (init?: string | URLSearchParams): URLSearchParams; -} +}; interface BlobPropertyBag { type?: string; @@ -1751,8 +1762,23 @@ interface AddEventListenerOptions extends EventListenerOptions { declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; + (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; +} +interface ForEachCallback { + (keyId: any, status: MediaKeyStatus): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface NotificationPermissionCallback { + (permission: NotificationPermission): void; } interface PositionCallback { (position: Position): void; @@ -1760,21 +1786,6 @@ interface PositionCallback { interface PositionErrorCallback { (error: PositionError): void; } -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface FunctionStringCallback { - (data: string): void; -} -interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; -} -interface NotificationPermissionCallback { - (permission: NotificationPermission): void; -} declare var onmessage: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any; declare function close(): void; declare function postMessage(message: any, transfer?: any[]): void; diff --git a/src/server/client.ts b/src/server/client.ts index 623b00f1ed3..aca52422e44 100644 --- a/src/server/client.ts +++ b/src/server/client.ts @@ -224,7 +224,7 @@ namespace ts.server { return { name, kind, kindModifiers, sortText, replacementSpan: convertedSpan }; } - return entry as { name: string, kind: string, kindModifiers: string, sortText: string }; + return entry as { name: string, kind: ScriptElementKind, kindModifiers: string, sortText: string }; }) }; } @@ -265,7 +265,7 @@ namespace ts.server { return { name: entry.name, containerName: entry.containerName || "", - containerKind: entry.containerKind || "", + containerKind: entry.containerKind || ScriptElementKind.unknown, kind: entry.kind, kindModifiers: entry.kindModifiers, matchKind: entry.matchKind, @@ -330,11 +330,11 @@ namespace ts.server { const start = this.lineOffsetToPosition(fileName, entry.start); const end = this.lineOffsetToPosition(fileName, entry.end); return { - containerKind: "", + containerKind: ScriptElementKind.unknown, containerName: "", fileName: fileName, textSpan: ts.createTextSpanFromBounds(start, end), - kind: "", + kind: ScriptElementKind.unknown, name: "" }; }); @@ -356,11 +356,11 @@ namespace ts.server { const start = this.lineOffsetToPosition(fileName, entry.start); const end = this.lineOffsetToPosition(fileName, entry.end); return { - containerKind: "", + containerKind: ScriptElementKind.unknown, containerName: "", fileName: fileName, textSpan: ts.createTextSpanFromBounds(start, end), - kind: "", + kind: ScriptElementKind.unknown, name: "" }; }); @@ -695,6 +695,46 @@ namespace ts.server { return response.body.map(entry => this.convertCodeActions(entry, fileName)); } + private createFileLocationOrRangeRequestArgs(positionOrRange: number | TextRange, fileName: string): protocol.FileLocationOrRangeRequestArgs { + if (typeof positionOrRange === "number") { + const { line, offset } = this.positionToOneBasedLineOffset(fileName, positionOrRange); + return { file: fileName, line, offset }; + } + const { line: startLine, offset: startOffset } = this.positionToOneBasedLineOffset(fileName, positionOrRange.pos); + const { line: endLine, offset: endOffset } = this.positionToOneBasedLineOffset(fileName, positionOrRange.end); + return { + file: fileName, + startLine, + startOffset, + endLine, + endOffset + }; + } + + getApplicableRefactors(fileName: string, positionOrRange: number | TextRange): ApplicableRefactorInfo[] { + const args = this.createFileLocationOrRangeRequestArgs(positionOrRange, fileName); + + const request = this.processRequest(CommandNames.GetApplicableRefactors, args); + const response = this.processResponse(request); + return response.body; + } + + getRefactorCodeActions( + fileName: string, + _formatOptions: FormatCodeSettings, + positionOrRange: number | TextRange, + refactorName: string) { + + const args = this.createFileLocationOrRangeRequestArgs(positionOrRange, fileName) as protocol.GetRefactorCodeActionsRequestArgs; + args.refactorName = refactorName; + + const request = this.processRequest(CommandNames.GetRefactorCodeActions, args); + const response = this.processResponse(request); + const codeActions = response.body.actions; + + return map(codeActions, codeAction => this.convertCodeActions(codeAction, fileName)); + } + convertCodeActions(entry: protocol.CodeAction, fileName: string): CodeAction { return { description: entry.description, diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 4699e1a1d4d..d8322f5e7c5 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -283,6 +283,7 @@ namespace ts.server { throttleWaitMilliseconds?: number; globalPlugins?: string[]; pluginProbeLocations?: string[]; + allowLocalPluginLoads?: boolean; } export class ProjectService { @@ -342,6 +343,7 @@ namespace ts.server { public readonly globalPlugins: ReadonlyArray; public readonly pluginProbeLocations: ReadonlyArray; + public readonly allowLocalPluginLoads: boolean; constructor(opts: ProjectServiceOptions) { this.host = opts.host; @@ -353,6 +355,7 @@ namespace ts.server { this.eventHandler = opts.eventHandler; this.globalPlugins = opts.globalPlugins || emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || emptyArray; + this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); diff --git a/src/server/project.ts b/src/server/project.ts index 56c394379a0..7dc4388bf39 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -13,13 +13,6 @@ namespace ts.server { External } - function remove(items: T[], item: T) { - const index = items.indexOf(item); - if (index >= 0) { - items.splice(index, 1); - } - } - function countEachFileTypes(infos: ScriptInfo[]): { js: number, jsx: number, ts: number, tsx: number, dts: number } { const result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 }; for (const info of infos) { @@ -732,7 +725,7 @@ namespace ts.server { // remove a root file from project protected removeRoot(info: ScriptInfo): void { - remove(this.rootFiles, info); + orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.remove(info.path); } } @@ -873,6 +866,12 @@ namespace ts.server { // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ const searchPaths = [combinePaths(host.getExecutingFilePath(), "../../.."), ...this.projectService.pluginProbeLocations]; + if (this.projectService.allowLocalPluginLoads) { + const local = getDirectoryPath(this.canonicalConfigFilePath); + this.projectService.logger.info(`Local plugin loading enabled; adding ${local} to search paths`); + searchPaths.unshift(local); + } + // Enable tsconfig-specified plugins if (options.plugins) { for (const pluginConfigEntry of options.plugins) { diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 428b69027c7..4e474edd0c4 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -2,99 +2,104 @@ * Declaration module describing the TypeScript Server protocol */ namespace ts.server.protocol { - export namespace CommandTypes { - export type Brace = "brace"; + // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`. + export const enum CommandTypes { + Brace = "brace", /* @internal */ - export type BraceFull = "brace-full"; - export type BraceCompletion = "braceCompletion"; - export type Change = "change"; - export type Close = "close"; - export type Completions = "completions"; + BraceFull = "brace-full", + BraceCompletion = "braceCompletion", + Change = "change", + Close = "close", + Completions = "completions", /* @internal */ - export type CompletionsFull = "completions-full"; - export type CompletionDetails = "completionEntryDetails"; - export type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; - export type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; - export type Configure = "configure"; - export type Definition = "definition"; + CompletionsFull = "completions-full", + CompletionDetails = "completionEntryDetails", + CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList", + CompileOnSaveEmitFile = "compileOnSaveEmitFile", + Configure = "configure", + Definition = "definition", /* @internal */ - export type DefinitionFull = "definition-full"; - export type Implementation = "implementation"; + DefinitionFull = "definition-full", + Implementation = "implementation", /* @internal */ - export type ImplementationFull = "implementation-full"; - export type Exit = "exit"; - export type Format = "format"; - export type Formatonkey = "formatonkey"; + ImplementationFull = "implementation-full", + Exit = "exit", + Format = "format", + Formatonkey = "formatonkey", /* @internal */ - export type FormatFull = "format-full"; + FormatFull = "format-full", /* @internal */ - export type FormatonkeyFull = "formatonkey-full"; + FormatonkeyFull = "formatonkey-full", /* @internal */ - export type FormatRangeFull = "formatRange-full"; - export type Geterr = "geterr"; - export type GeterrForProject = "geterrForProject"; - export type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; - export type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; - export type NavBar = "navbar"; + FormatRangeFull = "formatRange-full", + Geterr = "geterr", + GeterrForProject = "geterrForProject", + SemanticDiagnosticsSync = "semanticDiagnosticsSync", + SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", + NavBar = "navbar", /* @internal */ - export type NavBarFull = "navbar-full"; - export type Navto = "navto"; + NavBarFull = "navbar-full", + Navto = "navto", /* @internal */ - export type NavtoFull = "navto-full"; - export type NavTree = "navtree"; - export type NavTreeFull = "navtree-full"; - export type Occurrences = "occurrences"; - export type DocumentHighlights = "documentHighlights"; + NavtoFull = "navto-full", + NavTree = "navtree", + NavTreeFull = "navtree-full", + Occurrences = "occurrences", + DocumentHighlights = "documentHighlights", /* @internal */ - export type DocumentHighlightsFull = "documentHighlights-full"; - export type Open = "open"; - export type Quickinfo = "quickinfo"; + DocumentHighlightsFull = "documentHighlights-full", + Open = "open", + Quickinfo = "quickinfo", /* @internal */ - export type QuickinfoFull = "quickinfo-full"; - export type References = "references"; + QuickinfoFull = "quickinfo-full", + References = "references", /* @internal */ - export type ReferencesFull = "references-full"; - export type Reload = "reload"; - export type Rename = "rename"; + ReferencesFull = "references-full", + Reload = "reload", + Rename = "rename", /* @internal */ - export type RenameInfoFull = "rename-full"; + RenameInfoFull = "rename-full", /* @internal */ - export type RenameLocationsFull = "renameLocations-full"; - export type Saveto = "saveto"; - export type SignatureHelp = "signatureHelp"; + RenameLocationsFull = "renameLocations-full", + Saveto = "saveto", + SignatureHelp = "signatureHelp", /* @internal */ - export type SignatureHelpFull = "signatureHelp-full"; - export type TypeDefinition = "typeDefinition"; - export type ProjectInfo = "projectInfo"; - export type ReloadProjects = "reloadProjects"; - export type Unknown = "unknown"; - export type OpenExternalProject = "openExternalProject"; - export type OpenExternalProjects = "openExternalProjects"; - export type CloseExternalProject = "closeExternalProject"; + SignatureHelpFull = "signatureHelp-full", + TypeDefinition = "typeDefinition", + ProjectInfo = "projectInfo", + ReloadProjects = "reloadProjects", + Unknown = "unknown", + OpenExternalProject = "openExternalProject", + OpenExternalProjects = "openExternalProjects", + CloseExternalProject = "closeExternalProject", /* @internal */ - export type SynchronizeProjectList = "synchronizeProjectList"; + SynchronizeProjectList = "synchronizeProjectList", /* @internal */ - export type ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + ApplyChangedToOpenFiles = "applyChangedToOpenFiles", /* @internal */ - export type EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full", /* @internal */ - export type Cleanup = "cleanup"; + Cleanup = "cleanup", /* @internal */ - export type OutliningSpans = "outliningSpans"; - export type TodoComments = "todoComments"; - export type Indentation = "indentation"; - export type DocCommentTemplate = "docCommentTemplate"; + OutliningSpans = "outliningSpans", + TodoComments = "todoComments", + Indentation = "indentation", + DocCommentTemplate = "docCommentTemplate", /* @internal */ - export type CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full", /* @internal */ - export type NameOrDottedNameSpan = "nameOrDottedNameSpan"; + NameOrDottedNameSpan = "nameOrDottedNameSpan", /* @internal */ - export type BreakpointStatement = "breakpointStatement"; - export type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; - export type GetCodeFixes = "getCodeFixes"; + BreakpointStatement = "breakpointStatement", + CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", + GetCodeFixes = "getCodeFixes", /* @internal */ - export type GetCodeFixesFull = "getCodeFixes-full"; - export type GetSupportedCodeFixes = "getSupportedCodeFixes"; + GetCodeFixesFull = "getCodeFixes-full", + GetSupportedCodeFixes = "getSupportedCodeFixes", + + GetApplicableRefactors = "getApplicableRefactors", + GetRefactorCodeActions = "getRefactorCodeActions", + GetRefactorCodeActionsFull = "getRefactorCodeActions-full", } /** @@ -394,6 +399,54 @@ namespace ts.server.protocol { position?: number; } + export type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + + export interface GetApplicableRefactorsRequest extends Request { + command: CommandTypes.GetApplicableRefactors; + arguments: GetApplicableRefactorsRequestArgs; + } + + export type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs; + + export interface ApplicableRefactorInfo { + name: string; + description: string; + } + + export interface GetApplicableRefactorsResponse extends Response { + body?: ApplicableRefactorInfo[]; + } + + export interface GetRefactorCodeActionsRequest extends Request { + command: CommandTypes.GetRefactorCodeActions; + arguments: GetRefactorCodeActionsRequestArgs; + } + + export type GetRefactorCodeActionsRequestArgs = FileLocationOrRangeRequestArgs & { + /* The kind of the applicable refactor */ + refactorName: string; + }; + + export type RefactorCodeActions = { + actions: protocol.CodeAction[]; + renameLocation?: number + }; + + /* @internal */ + export type RefactorCodeActionsFull = { + actions: ts.CodeAction[]; + renameLocation?: number + }; + + export interface GetRefactorCodeActionsResponse extends Response { + body: RefactorCodeActions; + } + + /* @internal */ + export interface GetRefactorCodeActionsFullResponse extends Response { + body: RefactorCodeActionsFull; + } + /** * Request for the available codefixes at a specific position. */ @@ -402,10 +455,7 @@ namespace ts.server.protocol { arguments: CodeFixRequestArgs; } - /** - * Instances of this interface specify errorcodes on a specific location in a sourcefile. - */ - export interface CodeFixRequestArgs extends FileRequestArgs { + export interface FileRangeRequestArgs extends FileRequestArgs { /** * The line number for the request (1-based). */ @@ -437,7 +487,12 @@ namespace ts.server.protocol { */ /* @internal */ endPosition?: number; + } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ + export interface CodeFixRequestArgs extends FileRangeRequestArgs { /** * Errorcodes we want to get the fixes for. */ @@ -644,10 +699,9 @@ namespace ts.server.protocol { /** * Span augmented with extra information that denotes the kind of the highlighting to be used for span. - * Kind is taken from HighlightSpanKind type. */ export interface HighlightSpan extends TextSpan { - kind: string; + kind: HighlightSpanKind; } /** @@ -784,7 +838,7 @@ namespace ts.server.protocol { /** * The items's kind (such as 'className' or 'parameterName' or plain 'text'). */ - kind: string; + kind: ScriptElementKind; /** * Optional modifiers for the kind (such as 'public'). @@ -1298,7 +1352,7 @@ namespace ts.server.protocol { /** * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). */ - kind: string; + kind: ScriptElementKind; /** * Optional modifiers for the kind (such as 'public'). @@ -1517,7 +1571,7 @@ namespace ts.server.protocol { /** * The symbol's kind (such as 'className' or 'parameterName'). */ - kind: string; + kind: ScriptElementKind; /** * Optional modifiers for the kind (such as 'public'). */ @@ -1545,7 +1599,7 @@ namespace ts.server.protocol { /** * The symbol's kind (such as 'className' or 'parameterName'). */ - kind: string; + kind: ScriptElementKind; /** * Optional modifiers for the kind (such as 'public'). */ @@ -2004,7 +2058,7 @@ namespace ts.server.protocol { /** * The symbol's kind (such as 'className' or 'parameterName'). */ - kind: string; + kind: ScriptElementKind; /** * exact, substring, or prefix. @@ -2045,7 +2099,7 @@ namespace ts.server.protocol { /** * Kind of symbol's container symbol (if any). */ - containerKind?: string; + containerKind?: ScriptElementKind; } /** @@ -2118,7 +2172,7 @@ namespace ts.server.protocol { /** * The symbol's kind (such as 'className' or 'parameterName'). */ - kind: string; + kind: ScriptElementKind; /** * Optional modifiers for the kind (such as 'public'). @@ -2144,7 +2198,7 @@ namespace ts.server.protocol { /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ export interface NavigationTree { text: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; spans: TextSpan[]; childItems?: NavigationTree[]; @@ -2238,14 +2292,12 @@ namespace ts.server.protocol { body?: NavigationTree; } - export namespace IndentStyle { - export type None = "None"; - export type Block = "Block"; - export type Smart = "Smart"; + export const enum IndentStyle { + None = "None", + Block = "Block", + Smart = "Smart", } - export type IndentStyle = IndentStyle.None | IndentStyle.Block | IndentStyle.Smart; - export interface EditorSettings { baseIndentSize?: number; indentSize?: number; @@ -2267,6 +2319,7 @@ namespace ts.server.protocol { insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; @@ -2341,47 +2394,37 @@ namespace ts.server.protocol { [option: string]: CompilerOptionsValue | undefined; } - export namespace JsxEmit { - export type None = "None"; - export type Preserve = "Preserve"; - export type ReactNative = "ReactNative"; - export type React = "React"; + export const enum JsxEmit { + None = "None", + Preserve = "Preserve", + ReactNative = "ReactNative", + React = "React", } - export type JsxEmit = JsxEmit.None | JsxEmit.Preserve | JsxEmit.React | JsxEmit.ReactNative; - - export namespace ModuleKind { - export type None = "None"; - export type CommonJS = "CommonJS"; - export type AMD = "AMD"; - export type UMD = "UMD"; - export type System = "System"; - export type ES6 = "ES6"; - export type ES2015 = "ES2015"; + export const enum ModuleKind { + None = "None", + CommonJS = "CommonJS", + AMD = "AMD", + UMD = "UMD", + System = "System", + ES6 = "ES6", + ES2015 = "ES2015", } - export type ModuleKind = ModuleKind.None | ModuleKind.CommonJS | ModuleKind.AMD | ModuleKind.UMD | ModuleKind.System | ModuleKind.ES6 | ModuleKind.ES2015; - - export namespace ModuleResolutionKind { - export type Classic = "Classic"; - export type Node = "Node"; + export const enum ModuleResolutionKind { + Classic = "Classic", + Node = "Node", } - export type ModuleResolutionKind = ModuleResolutionKind.Classic | ModuleResolutionKind.Node; - - export namespace NewLineKind { - export type Crlf = "Crlf"; - export type Lf = "Lf"; + export const enum NewLineKind { + Crlf = "Crlf", + Lf = "Lf", } - export type NewLineKind = NewLineKind.Crlf | NewLineKind.Lf; - - export namespace ScriptTarget { - export type ES3 = "ES3"; - export type ES5 = "ES5"; - export type ES6 = "ES6"; - export type ES2015 = "ES2015"; + export const enum ScriptTarget { + ES3 = "ES3", + ES5 = "ES5", + ES6 = "ES6", + ES2015 = "ES2015", } - - export type ScriptTarget = ScriptTarget.ES3 | ScriptTarget.ES5 | ScriptTarget.ES6 | ScriptTarget.ES2015; } diff --git a/src/server/server.ts b/src/server/server.ts index 79cfc3882ae..ed3e2dd8207 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -16,6 +16,7 @@ namespace ts.server { telemetryEnabled: boolean; globalPlugins: string[]; pluginProbeLocations: string[]; + allowLocalPluginLoads: boolean; } const net: { @@ -403,7 +404,8 @@ namespace ts.server { logger, canUseEvents, globalPlugins: options.globalPlugins, - pluginProbeLocations: options.pluginProbeLocations}); + pluginProbeLocations: options.pluginProbeLocations, + allowLocalPluginLoads: options.allowLocalPluginLoads }); if (telemetryEnabled && typingsInstaller) { typingsInstaller.setTelemetrySender(this); @@ -708,12 +710,11 @@ namespace ts.server { } sys.require = (initialDir: string, moduleName: string): RequireResult => { - const result = nodeModuleNameResolverWorker(moduleName, initialDir + "/program.ts", { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, sys, /*cache*/ undefined, /*jsOnly*/ true); try { - return { module: require(result.resolvedModule.resolvedFileName), error: undefined }; + return { module: require(resolveJavaScriptModule(moduleName, initialDir, sys)), error: undefined }; } - catch (e) { - return { module: undefined, error: e }; + catch (error) { + return { module: undefined, error }; } }; @@ -744,6 +745,7 @@ namespace ts.server { const globalPlugins = (findArgument("--globalPlugins") || "").split(","); const pluginProbeLocations = (findArgument("--pluginProbeLocations") || "").split(","); + const allowLocalPluginLoads = hasArgument("--allowLocalPluginLoads"); const useSingleInferredProject = hasArgument("--useSingleInferredProject"); const disableAutomaticTypingAcquisition = hasArgument("--disableAutomaticTypingAcquisition"); @@ -761,7 +763,8 @@ namespace ts.server { telemetryEnabled, logger, globalPlugins, - pluginProbeLocations + pluginProbeLocations, + allowLocalPluginLoads }; const ioSession = new IOSession(options); diff --git a/src/server/session.ts b/src/server/session.ts index ca036f4dfe0..846607cd5ca 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -100,7 +100,7 @@ namespace ts.server { } export interface EventSender { - event(payload: any, eventName: string): void; + event(payload: T, eventName: string): void; } function allEditsBeforePos(edits: ts.TextChange[], pos: number) { @@ -112,100 +112,7 @@ namespace ts.server { return true; } - export namespace CommandNames { - export const Brace: protocol.CommandTypes.Brace = "brace"; - /* @internal */ - export const BraceFull: protocol.CommandTypes.BraceFull = "brace-full"; - export const BraceCompletion: protocol.CommandTypes.BraceCompletion = "braceCompletion"; - export const Change: protocol.CommandTypes.Change = "change"; - export const Close: protocol.CommandTypes.Close = "close"; - export const Completions: protocol.CommandTypes.Completions = "completions"; - /* @internal */ - export const CompletionsFull: protocol.CommandTypes.CompletionsFull = "completions-full"; - export const CompletionDetails: protocol.CommandTypes.CompletionDetails = "completionEntryDetails"; - export const CompileOnSaveAffectedFileList: protocol.CommandTypes.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; - export const CompileOnSaveEmitFile: protocol.CommandTypes.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; - export const Configure: protocol.CommandTypes.Configure = "configure"; - export const Definition: protocol.CommandTypes.Definition = "definition"; - /* @internal */ - export const DefinitionFull: protocol.CommandTypes.DefinitionFull = "definition-full"; - export const Exit: protocol.CommandTypes.Exit = "exit"; - export const Format: protocol.CommandTypes.Format = "format"; - export const Formatonkey: protocol.CommandTypes.Formatonkey = "formatonkey"; - /* @internal */ - export const FormatFull: protocol.CommandTypes.FormatFull = "format-full"; - /* @internal */ - export const FormatonkeyFull: protocol.CommandTypes.FormatonkeyFull = "formatonkey-full"; - /* @internal */ - export const FormatRangeFull: protocol.CommandTypes.FormatRangeFull = "formatRange-full"; - export const Geterr: protocol.CommandTypes.Geterr = "geterr"; - export const GeterrForProject: protocol.CommandTypes.GeterrForProject = "geterrForProject"; - export const Implementation: protocol.CommandTypes.Implementation = "implementation"; - /* @internal */ - export const ImplementationFull: protocol.CommandTypes.ImplementationFull = "implementation-full"; - export const SemanticDiagnosticsSync: protocol.CommandTypes.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; - export const SyntacticDiagnosticsSync: protocol.CommandTypes.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; - export const NavBar: protocol.CommandTypes.NavBar = "navbar"; - /* @internal */ - export const NavBarFull: protocol.CommandTypes.NavBarFull = "navbar-full"; - export const NavTree: protocol.CommandTypes.NavTree = "navtree"; - export const NavTreeFull: protocol.CommandTypes.NavTreeFull = "navtree-full"; - export const Navto: protocol.CommandTypes.Navto = "navto"; - /* @internal */ - export const NavtoFull: protocol.CommandTypes.NavtoFull = "navto-full"; - export const Occurrences: protocol.CommandTypes.Occurrences = "occurrences"; - export const DocumentHighlights: protocol.CommandTypes.DocumentHighlights = "documentHighlights"; - /* @internal */ - export const DocumentHighlightsFull: protocol.CommandTypes.DocumentHighlightsFull = "documentHighlights-full"; - export const Open: protocol.CommandTypes.Open = "open"; - export const Quickinfo: protocol.CommandTypes.Quickinfo = "quickinfo"; - /* @internal */ - export const QuickinfoFull: protocol.CommandTypes.QuickinfoFull = "quickinfo-full"; - export const References: protocol.CommandTypes.References = "references"; - /* @internal */ - export const ReferencesFull: protocol.CommandTypes.ReferencesFull = "references-full"; - export const Reload: protocol.CommandTypes.Reload = "reload"; - export const Rename: protocol.CommandTypes.Rename = "rename"; - /* @internal */ - export const RenameInfoFull: protocol.CommandTypes.RenameInfoFull = "rename-full"; - /* @internal */ - export const RenameLocationsFull: protocol.CommandTypes.RenameLocationsFull = "renameLocations-full"; - export const Saveto: protocol.CommandTypes.Saveto = "saveto"; - export const SignatureHelp: protocol.CommandTypes.SignatureHelp = "signatureHelp"; - /* @internal */ - export const SignatureHelpFull: protocol.CommandTypes.SignatureHelpFull = "signatureHelp-full"; - export const TypeDefinition: protocol.CommandTypes.TypeDefinition = "typeDefinition"; - export const ProjectInfo: protocol.CommandTypes.ProjectInfo = "projectInfo"; - export const ReloadProjects: protocol.CommandTypes.ReloadProjects = "reloadProjects"; - export const Unknown: protocol.CommandTypes.Unknown = "unknown"; - export const OpenExternalProject: protocol.CommandTypes.OpenExternalProject = "openExternalProject"; - export const OpenExternalProjects: protocol.CommandTypes.OpenExternalProjects = "openExternalProjects"; - export const CloseExternalProject: protocol.CommandTypes.CloseExternalProject = "closeExternalProject"; - /* @internal */ - export const SynchronizeProjectList: protocol.CommandTypes.SynchronizeProjectList = "synchronizeProjectList"; - /* @internal */ - export const ApplyChangedToOpenFiles: protocol.CommandTypes.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; - /* @internal */ - export const EncodedSemanticClassificationsFull: protocol.CommandTypes.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; - /* @internal */ - export const Cleanup: protocol.CommandTypes.Cleanup = "cleanup"; - /* @internal */ - export const OutliningSpans: protocol.CommandTypes.OutliningSpans = "outliningSpans"; - export const TodoComments: protocol.CommandTypes.TodoComments = "todoComments"; - export const Indentation: protocol.CommandTypes.Indentation = "indentation"; - export const DocCommentTemplate: protocol.CommandTypes.DocCommentTemplate = "docCommentTemplate"; - /* @internal */ - export const CompilerOptionsDiagnosticsFull: protocol.CommandTypes.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; - /* @internal */ - export const NameOrDottedNameSpan: protocol.CommandTypes.NameOrDottedNameSpan = "nameOrDottedNameSpan"; - /* @internal */ - export const BreakpointStatement: protocol.CommandTypes.BreakpointStatement = "breakpointStatement"; - export const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; - export const GetCodeFixes: protocol.CommandTypes.GetCodeFixes = "getCodeFixes"; - /* @internal */ - export const GetCodeFixesFull: protocol.CommandTypes.GetCodeFixesFull = "getCodeFixes-full"; - export const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes = "getSupportedCodeFixes"; - } + export import CommandNames = protocol.CommandTypes; export function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string { const verboseLogging = logger.hasLevel(LogLevel.verbose); @@ -348,6 +255,7 @@ namespace ts.server { globalPlugins?: string[]; pluginProbeLocations?: string[]; + allowLocalPluginLoads?: boolean; } export class Session implements EventSender { @@ -401,7 +309,8 @@ namespace ts.server { throttleWaitMilliseconds, eventHandler: this.eventHandler, globalPlugins: opts.globalPlugins, - pluginProbeLocations: opts.pluginProbeLocations + pluginProbeLocations: opts.pluginProbeLocations, + allowLocalPluginLoads: opts.allowLocalPluginLoads }; this.projectService = new ProjectService(settings); this.gcTimer = new GcTimer(this.host, /*delay*/ 7000, this.logger); @@ -430,7 +339,7 @@ namespace ts.server { break; case ProjectLanguageServiceStateEvent: const eventName: protocol.ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; - this.event({ + this.event({ projectName: event.data.project.getProjectName(), languageServiceEnabled: event.data.languageServiceEnabled }, eventName); @@ -474,7 +383,7 @@ namespace ts.server { this.send(ev); } - public event(info: any, eventName: string) { + public event(info: T, eventName: string) { const ev: protocol.Event = { seq: 0, type: "event", @@ -509,7 +418,7 @@ namespace ts.server { } const bakedDiags = diags.map((diag) => formatDiag(file, project, diag)); - this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); + this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); } catch (err) { this.logError(err, "semantic check"); @@ -521,7 +430,7 @@ namespace ts.server { const diags = project.getLanguageService().getSyntacticDiagnostics(file); if (diags) { const bakedDiags = diags.map((diag) => formatDiag(file, project, diag)); - this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); + this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); } } catch (err) { @@ -1364,8 +1273,8 @@ namespace ts.server { return !items ? undefined : simplifiedResult - ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) - : items; + ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) + : items; } private decorateNavigationTree(tree: ts.NavigationTree, scriptInfo: ScriptInfo): protocol.NavigationTree { @@ -1391,8 +1300,8 @@ namespace ts.server { return !tree ? undefined : simplifiedResult - ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) - : tree; + ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) + : tree; } private getNavigateToItems(args: protocol.NavtoRequestArgs, simplifiedResult: boolean): protocol.NavtoItem[] | NavigateToItem[] { @@ -1479,6 +1388,60 @@ namespace ts.server { return ts.getSupportedCodeFixes(); } + private isLocation(locationOrSpan: protocol.FileLocationOrRangeRequestArgs): locationOrSpan is protocol.FileLocationRequestArgs { + return (locationOrSpan).line !== undefined; + } + + private extractPositionAndRange(args: protocol.FileLocationOrRangeRequestArgs, scriptInfo: ScriptInfo): { position: number, textRange: TextRange } { + let position: number = undefined; + let textRange: TextRange; + if (this.isLocation(args)) { + position = getPosition(args); + } + else { + const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo); + textRange = { pos: startPosition, end: endPosition }; + } + return { position, textRange }; + + function getPosition(loc: protocol.FileLocationRequestArgs) { + return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); + } + } + + private getApplicableRefactors(args: protocol.GetApplicableRefactorsRequestArgs): protocol.ApplicableRefactorInfo[] { + const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + const { position, textRange } = this.extractPositionAndRange(args, scriptInfo); + return project.getLanguageService().getApplicableRefactors(file, position || textRange); + } + + private getRefactorCodeActions(args: protocol.GetRefactorCodeActionsRequestArgs, simplifiedResult: boolean): protocol.RefactorCodeActions | protocol.RefactorCodeActionsFull { + const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + const { position, textRange } = this.extractPositionAndRange(args, scriptInfo); + + const result: ts.CodeAction[] = project.getLanguageService().getRefactorCodeActions( + file, + this.projectService.getFormatCodeOptions(), + position || textRange, + args.refactorName + ); + + if (simplifiedResult) { + // Not full + return { + actions: result.map(action => this.mapCodeAction(action, scriptInfo)) + }; + } + else { + // Full + return { + actions: result + }; + } + } + private getCodeFixes(args: protocol.CodeFixRequestArgs, simplifiedResult: boolean): protocol.CodeAction[] | CodeAction[] { if (args.errorCodes.length === 0) { return undefined; @@ -1486,8 +1449,7 @@ namespace ts.server { const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args); const scriptInfo = project.getScriptInfoForNormalizedPath(file); - const startPosition = getStartPosition(); - const endPosition = getEndPosition(); + const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo); const formatOptions = this.projectService.getFormatCodeOptions(file); const codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, formatOptions); @@ -1500,14 +1462,28 @@ namespace ts.server { else { return codeActions; } + } - function getStartPosition() { - return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + private getStartAndEndPosition(args: protocol.FileRangeRequestArgs, scriptInfo: ScriptInfo) { + let startPosition: number = undefined, endPosition: number = undefined; + if (args.startPosition !== undefined) { + startPosition = args.startPosition; + } + else { + startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + // save the result so we don't always recompute + args.startPosition = startPosition; } - function getEndPosition() { - return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + if (args.endPosition !== undefined) { + endPosition = args.endPosition; } + else { + endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + args.endPosition = endPosition; + } + + return { startPosition, endPosition }; } private mapCodeAction(codeAction: CodeAction, scriptInfo: ScriptInfo): protocol.CodeAction { @@ -1538,8 +1514,8 @@ namespace ts.server { return !spans ? undefined : simplifiedResult - ? spans.map(span => this.decorateSpan(span, scriptInfo)) - : spans; + ? spans.map(span => this.decorateSpan(span, scriptInfo)) + : spans; } private getDiagnosticsForProject(next: NextStep, delay: number, fileName: string): void { @@ -1844,6 +1820,15 @@ namespace ts.server { }, [CommandNames.GetSupportedCodeFixes]: () => { return this.requiredResponse(this.getSupportedCodeFixes()); + }, + [CommandNames.GetApplicableRefactors]: (request: protocol.GetApplicableRefactorsRequest) => { + return this.requiredResponse(this.getApplicableRefactors(request.arguments)); + }, + [CommandNames.GetRefactorCodeActions]: (request: protocol.GetRefactorCodeActionsRequest) => { + return this.requiredResponse(this.getRefactorCodeActions(request.arguments, /*simplifiedResult*/ true)); + }, + [CommandNames.GetRefactorCodeActionsFull]: (request: protocol.GetRefactorCodeActionsRequest) => { + return this.requiredResponse(this.getRefactorCodeActions(request.arguments, /*simplifiedResult*/ false)); } }); @@ -1901,7 +1886,7 @@ namespace ts.server { let request: protocol.Request; try { request = JSON.parse(message); - const {response, responseRequired} = this.executeCommand(request); + const { response, responseRequired } = this.executeCommand(request); if (this.logger.hasLevel(LogLevel.requestTime)) { const elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); diff --git a/src/server/typingsInstaller/nodeTypingsInstaller.ts b/src/server/typingsInstaller/nodeTypingsInstaller.ts index 895a4e17cc7..1182450ce81 100644 --- a/src/server/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/server/typingsInstaller/nodeTypingsInstaller.ts @@ -96,6 +96,9 @@ namespace ts.server.typingsInstaller { this.log.writeLine(`Updating ${TypesRegistryPackageName} npm package...`); } this.execSync(`${this.npmPath} install ${TypesRegistryPackageName}`, { cwd: globalTypingsCacheLocation, stdio: "ignore" }); + if (this.log.isEnabled()) { + this.log.writeLine(`Updated ${TypesRegistryPackageName} npm package`); + } } catch (e) { if (this.log.isEnabled()) { diff --git a/src/services/breakpoints.ts b/src/services/breakpoints.ts index e47f6d016c7..38da43bdee8 100644 --- a/src/services/breakpoints.ts +++ b/src/services/breakpoints.ts @@ -14,7 +14,7 @@ namespace ts.BreakpointResolver { return undefined; } - let tokenAtLocation = getTokenAtPosition(sourceFile, position); + let tokenAtLocation = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); const lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { // Get previous token if the token is returned starts on new line diff --git a/src/services/classifier.ts b/src/services/classifier.ts index 0deff253212..acee8fe4b0e 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -573,7 +573,7 @@ namespace ts { } } - function getClassificationTypeName(type: ClassificationType) { + function getClassificationTypeName(type: ClassificationType): ClassificationTypeNames { switch (type) { case ClassificationType.comment: return ClassificationTypeNames.comment; case ClassificationType.identifier: return ClassificationTypeNames.identifier; diff --git a/src/services/codeFixProvider.ts b/src/services/codeFixProvider.ts index bab5356e99c..6ff78572f82 100644 --- a/src/services/codeFixProvider.ts +++ b/src/services/codeFixProvider.ts @@ -19,14 +19,14 @@ namespace ts { export namespace codefix { const codeFixes: CodeFix[][] = []; - export function registerCodeFix(action: CodeFix) { - forEach(action.errorCodes, error => { + export function registerCodeFix(codeFix: CodeFix) { + forEach(codeFix.errorCodes, error => { let fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } diff --git a/src/services/codefixes/disableJsDiagnostics.ts b/src/services/codefixes/disableJsDiagnostics.ts index 7fa5c5bf23f..b5f9e5587a3 100644 --- a/src/services/codefixes/disableJsDiagnostics.ts +++ b/src/services/codefixes/disableJsDiagnostics.ts @@ -22,7 +22,7 @@ namespace ts.codefix { // We also want to check if the previous line holds a comment for a node on the next line // if so, we do not want to separate the node from its comment if we can. if (!isInComment(sourceFile, startPosition) && !isInString(sourceFile, startPosition) && !isInTemplateString(sourceFile, startPosition)) { - const token = getTouchingToken(sourceFile, startPosition); + const token = getTouchingToken(sourceFile, startPosition, /*includeJsDocComment*/ false); const tokenLeadingCommnets = getLeadingCommentRangesOfNode(token, sourceFile); if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) { return { diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index 8e1d0ac2f29..64e7e560094 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -1,7 +1,8 @@ /* @internal */ namespace ts.codefix { registerCodeFix({ - errorCodes: [Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [Diagnostics.Property_0_does_not_exist_on_type_1.code, + Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); @@ -12,7 +13,7 @@ namespace ts.codefix { // This is the identifier of the missing property. eg: // this.missing = 1; // ^^^^^^^ - const token = getTokenAtPosition(sourceFile, start); + const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); if (token.kind !== SyntaxKind.Identifier) { return undefined; @@ -110,16 +111,16 @@ namespace ts.codefix { if (!isStatic) { const stringTypeNode = createKeywordTypeNode(SyntaxKind.StringKeyword); const indexingParameter = createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, "x", - /*questionToken*/ undefined, + /*questionToken*/ undefined, stringTypeNode, - /*initializer*/ undefined); - const indexSignature = createIndexSignatureDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, + /*initializer*/ undefined); + const indexSignature = createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [indexingParameter], typeNode); @@ -135,4 +136,4 @@ namespace ts.codefix { return actions; } } -} \ No newline at end of file +} diff --git a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts index 62f89b1a21a..768eaf752b7 100644 --- a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts +++ b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts @@ -15,7 +15,7 @@ namespace ts.codefix { const start = context.span.start; // This is the identifier in the case of a class declaration // or the class keyword token in the case of a class expression. - const token = getTokenAtPosition(sourceFile, start); + const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); const checker = context.program.getTypeChecker(); if (isClassLike(token.parent)) { diff --git a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts index 3b1b99febb0..bed9621b729 100644 --- a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts +++ b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts @@ -8,7 +8,7 @@ namespace ts.codefix { function getActionForClassLikeIncorrectImplementsInterface(context: CodeFixContext): CodeAction[] | undefined { const sourceFile = context.sourceFile; const start = context.span.start; - const token = getTokenAtPosition(sourceFile, start); + const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); const checker = context.program.getTypeChecker(); const classDeclaration = getContainingClass(token); diff --git a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts index 2217dda8b0c..56128be9d07 100644 --- a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts +++ b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts @@ -5,7 +5,7 @@ namespace ts.codefix { getCodeActions: (context: CodeFixContext) => { const sourceFile = context.sourceFile; - const token = getTokenAtPosition(sourceFile, context.span.start); + const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== SyntaxKind.ThisKeyword) { return undefined; } diff --git a/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts b/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts index 822c34842fd..517a79e39bd 100644 --- a/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts +++ b/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts @@ -4,7 +4,7 @@ namespace ts.codefix { errorCodes: [Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], getCodeActions: (context: CodeFixContext) => { const sourceFile = context.sourceFile; - const token = getTokenAtPosition(sourceFile, context.span.start); + const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== SyntaxKind.ConstructorKeyword) { return undefined; diff --git a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts index 80d4345a943..d23f61d0f92 100644 --- a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts +++ b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts @@ -5,7 +5,7 @@ namespace ts.codefix { getCodeActions: (context: CodeFixContext) => { const sourceFile = context.sourceFile; const start = context.span.start; - const token = getTokenAtPosition(sourceFile, start); + const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); const classDeclNode = getContainingClass(token); if (!(token.kind === SyntaxKind.Identifier && isClassLike(classDeclNode))) { return undefined; diff --git a/src/services/codefixes/fixForgottenThisPropertyAccess.ts b/src/services/codefixes/fixForgottenThisPropertyAccess.ts index 711a3289a27..6925b557755 100644 --- a/src/services/codefixes/fixForgottenThisPropertyAccess.ts +++ b/src/services/codefixes/fixForgottenThisPropertyAccess.ts @@ -4,7 +4,7 @@ namespace ts.codefix { errorCodes: [Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], getCodeActions: (context: CodeFixContext) => { const sourceFile = context.sourceFile; - const token = getTokenAtPosition(sourceFile, context.span.start); + const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== SyntaxKind.Identifier) { return undefined; } diff --git a/src/services/codefixes/fixSpelling.ts b/src/services/codefixes/fixSpelling.ts new file mode 100644 index 00000000000..c8f539e8d34 --- /dev/null +++ b/src/services/codefixes/fixSpelling.ts @@ -0,0 +1,53 @@ +/* @internal */ +namespace ts.codefix { + registerCodeFix({ + errorCodes: [Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + + function getActionsForCorrectSpelling(context: CodeFixContext): CodeAction[] | undefined { + const sourceFile = context.sourceFile; + + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + const node = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852 + const checker = context.program.getTypeChecker(); + let suggestion: string; + if (node.kind === SyntaxKind.Identifier && isPropertyAccessExpression(node.parent)) { + const containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node as Identifier, containingType); + } + else { + const meaning = getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + + function convertSemanticMeaningToSymbolFlags(meaning: SemanticMeaning): SymbolFlags { + let flags = 0; + if (meaning & SemanticMeaning.Namespace) { + flags |= SymbolFlags.Namespace; + } + if (meaning & SemanticMeaning.Type) { + flags |= SymbolFlags.Type; + } + if (meaning & SemanticMeaning.Value) { + flags |= SymbolFlags.Value; + } + return flags; + } +} diff --git a/src/services/codefixes/fixes.ts b/src/services/codefixes/fixes.ts index ae1643dfa3b..c2e2509a28e 100644 --- a/src/services/codefixes/fixes.ts +++ b/src/services/codefixes/fixes.ts @@ -1,5 +1,6 @@ /// /// +/// /// /// /// diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 0de04d7a9b9..39d8e13dde9 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -63,7 +63,7 @@ namespace ts.codefix { const declaration = declarations[0] as Declaration; // Clone name to remove leading trivia. - const name = getSynthesizedClone(declaration.name); + const name = getSynthesizedClone(getNameOfDeclaration(declaration)) as PropertyName; const visibilityModifier = createVisibilityModifier(getModifierFlags(declaration)); const modifiers = visibilityModifier ? createNodeArray([visibilityModifier]) : undefined; const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -130,7 +130,7 @@ namespace ts.codefix { } function signatureToMethodDeclaration(signature: Signature, enclosingDeclaration: Node, body?: Block) { - const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration); + const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration, NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -200,7 +200,7 @@ namespace ts.codefix { } export function createStubbedMethod(modifiers: Modifier[], name: PropertyName, optional: boolean, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], returnType: TypeNode | undefined) { - return createMethodDeclaration( + return createMethod( /*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, @@ -231,4 +231,4 @@ namespace ts.codefix { } return undefined; } -} \ No newline at end of file +} diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 9322f09cb86..53ec99fac81 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -3,6 +3,7 @@ namespace ts.codefix { registerCodeFix({ errorCodes: [ Diagnostics.Cannot_find_name_0.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, Diagnostics.Cannot_find_namespace_0.code, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ], @@ -127,7 +128,7 @@ namespace ts.codefix { const allSourceFiles = context.program.getSourceFiles(); const useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - const token = getTokenAtPosition(sourceFile, context.span.start); + const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); const name = token.getText(); const symbolIdActionMap = new ImportCodeActionMap(); @@ -522,7 +523,7 @@ namespace ts.codefix { catch (e) { } } - return relativeFileName; + return getPackageNameFromAtTypesDirectory(relativeFileName); } } diff --git a/src/services/codefixes/unusedIdentifierFixes.ts b/src/services/codefixes/unusedIdentifierFixes.ts index 422a28098a6..5d85979fcf9 100644 --- a/src/services/codefixes/unusedIdentifierFixes.ts +++ b/src/services/codefixes/unusedIdentifierFixes.ts @@ -9,11 +9,11 @@ namespace ts.codefix { const sourceFile = context.sourceFile; const start = context.span.start; - let token = getTokenAtPosition(sourceFile, start); + let token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); // this handles var ["computed"] = 12; if (token.kind === SyntaxKind.OpenBracketToken) { - token = getTokenAtPosition(sourceFile, start + 1); + token = getTokenAtPosition(sourceFile, start + 1, /*includeJsDocComment*/ false); } switch (token.kind) { @@ -48,11 +48,11 @@ namespace ts.codefix { case SyntaxKind.TypeParameter: const typeParameters = (token.parent.parent).typeParameters; if (typeParameters.length === 1) { - const previousToken = getTokenAtPosition(sourceFile, typeParameters.pos - 1); + const previousToken = getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); if (!previousToken || previousToken.kind !== SyntaxKind.LessThanToken) { return deleteRange(typeParameters); } - const nextToken = getTokenAtPosition(sourceFile, typeParameters.end); + const nextToken = getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); if (!nextToken || nextToken.kind !== SyntaxKind.GreaterThanToken) { return deleteRange(typeParameters); } @@ -99,7 +99,7 @@ namespace ts.codefix { else { // import |d,| * as ns from './file' const start = importClause.name.getStart(sourceFile); - const nextToken = getTokenAtPosition(sourceFile, importClause.name.end); + const nextToken = getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); if (nextToken && nextToken.kind === SyntaxKind.CommaToken) { // shift first non-whitespace position after comma to the start position of the node return deleteRange({ pos: start, end: skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); @@ -116,7 +116,7 @@ namespace ts.codefix { return deleteNode(importDecl); } else { - const previousToken = getTokenAtPosition(sourceFile, namespaceImport.pos - 1); + const previousToken = getTokenAtPosition(sourceFile, namespaceImport.pos - 1, /*includeJsDocComment*/ false); if (previousToken && previousToken.kind === SyntaxKind.CommaToken) { const startPosition = textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, textChanges.Position.FullStart); return deleteRange({ pos: startPosition, end: namespaceImport.end }); diff --git a/src/services/completions.ts b/src/services/completions.ts index 6ac3762b4c7..a895be8a7da 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -18,7 +18,7 @@ namespace ts.Completions { return undefined; } - const { symbols, isGlobalCompletion, isMemberCompletion, isNewIdentifierLocation, location, requestJsDocTagName, requestJsDocTag } = completionData; + const { symbols, isGlobalCompletion, isMemberCompletion, isNewIdentifierLocation, location, requestJsDocTagName, requestJsDocTag, hasFilteredClassMemberKeywords } = completionData; if (requestJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion @@ -52,7 +52,7 @@ namespace ts.Completions { sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } @@ -60,8 +60,11 @@ namespace ts.Completions { getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); } + if (hasFilteredClassMemberKeywords) { + addRange(entries, classMemberKeywordCompletions); + } // Add keywords if this is not a member completion list - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { addRange(entries, keywordCompletions); } @@ -221,11 +224,12 @@ namespace ts.Completions { function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo: SignatureHelp.ArgumentListInfo, typeChecker: TypeChecker): CompletionInfo | undefined { const candidates: Signature[] = []; const entries: CompletionEntry[] = []; + const uniques = createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (const candidate of candidates) { - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { @@ -258,25 +262,29 @@ namespace ts.Completions { return undefined; } - function addStringLiteralCompletionsFromType(type: Type, result: Push, typeChecker: TypeChecker): void { + function addStringLiteralCompletionsFromType(type: Type, result: Push, typeChecker: TypeChecker, uniques = createMap()): void { if (type && type.flags & TypeFlags.TypeParameter) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; } if (type.flags & TypeFlags.Union) { for (const t of (type).types) { - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & TypeFlags.StringLiteral) { - result.push({ - name: (type).text, - kindModifiers: ScriptElementKindModifier.none, - kind: ScriptElementKind.variableElement, - sortText: "0" - }); + const name = (type).value; + if (!uniques.has(name)) { + uniques.set(name, true); + result.push({ + name, + kindModifiers: ScriptElementKindModifier.none, + kind: ScriptElementKind.variableElement, + sortText: "0" + }); + } } } @@ -346,12 +354,12 @@ namespace ts.Completions { let requestJsDocTag = false; let start = timestamp(); - const currentToken = getTokenAtPosition(sourceFile, position); + const currentToken = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 log("getCompletionData: Get current token: " + (timestamp() - start)); start = timestamp(); // Completion not allowed inside comments, bail out if this is the case - const insideComment = isInsideComment(sourceFile, currentToken, position); + const insideComment = isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (timestamp() - start)); if (insideComment) { @@ -406,7 +414,7 @@ namespace ts.Completions { } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName, requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName, requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { @@ -441,7 +449,7 @@ namespace ts.Completions { let isRightOfOpenTag = false; let isStartingCloseTag = false; - let location = getTouchingPropertyName(sourceFile, position); + let location = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 if (contextToken) { // Bail out if this is a known invalid completion location if (isCompletionListBlocker(contextToken)) { @@ -505,6 +513,7 @@ namespace ts.Completions { let isGlobalCompletion = false; let isMemberCompletion: boolean; let isNewIdentifierLocation: boolean; + let hasFilteredClassMemberKeywords = false; let symbols: Symbol[] = []; if (isRightOfDot) { @@ -542,7 +551,7 @@ namespace ts.Completions { log("getCompletionData: Semantic work: " + (timestamp() - semanticStart)); - return { symbols, isGlobalCompletion, isMemberCompletion, isNewIdentifierLocation, location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName, requestJsDocTag }; + return { symbols, isGlobalCompletion, isMemberCompletion, isNewIdentifierLocation, location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName, requestJsDocTag, hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols(): void { // Right of dot member completion list @@ -599,6 +608,7 @@ namespace ts.Completions { function tryGetGlobalSymbols(): boolean { let objectLikeContainer: ObjectLiteralExpression | BindingPattern; let namedImportsOrExports: NamedImportsOrExports; + let classLikeContainer: ClassLikeDeclaration; let jsxContainer: JsxOpeningLikeElement; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { @@ -611,6 +621,12 @@ namespace ts.Completions { return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + // cursor inside class declaration + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; + } + if (jsxContainer = tryGetContainingJsxElement(contextToken)) { let attrsType: Type; if ((jsxContainer.kind === SyntaxKind.JsxSelfClosingElement) || (jsxContainer.kind === SyntaxKind.JsxOpeningElement)) { @@ -813,19 +829,16 @@ namespace ts.Completions { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; - let typeForObject: Type; + let typeMembers: Symbol[]; let existingMembers: Declaration[]; if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; - - // If the object literal is being assigned to something of type 'null | { hello: string }', - // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); - + const typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = (objectLikeContainer).properties; } else if (objectLikeContainer.kind === SyntaxKind.ObjectBindingPattern) { @@ -849,7 +862,10 @@ namespace ts.Completions { } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + const typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) return false; + // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = (objectLikeContainer).elements; } } @@ -861,11 +877,6 @@ namespace ts.Completions { Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - - const typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); @@ -913,6 +924,62 @@ namespace ts.Completions { return true; } + /** + * Aggregates relevant symbols for completion in class declaration + * Relevant symbols are stored in the captured 'symbols' variable. + */ + function getGetClassLikeCompletionSymbols(classLikeDeclaration: ClassLikeDeclaration) { + // We're looking up possible property names from parent type. + isMemberCompletion = true; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for class elements + hasFilteredClassMemberKeywords = true; + + const baseTypeNode = getClassExtendsHeritageClauseElement(classLikeDeclaration); + const implementsTypeNodes = getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { + const classElement = contextToken.parent; + let classElementModifierFlags = isClassElement(classElement) && getModifierFlags(classElement); + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === SyntaxKind.Identifier && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | ModifierFlags.Private; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | ModifierFlags.Static; + break; + } + } + + // No member list for private methods + if (!(classElementModifierFlags & ModifierFlags.Private)) { + let baseClassTypeToGetPropertiesFrom: Type; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & ModifierFlags.Static) { + // Use static class to get property symbols from + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation( + baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + const implementedInterfaceTypePropertySymbols = (classElementModifierFlags & ModifierFlags.Static) ? + undefined : + flatMap(implementsTypeNodes, typeNode => typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode))); + + // List of property symbols of base type that are not private and already implemented + symbols = filterClassMembersList( + baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, + implementedInterfaceTypePropertySymbols, + classLikeDeclaration.members, + classElementModifierFlags); + } + } + } + /** * Returns the immediate owning object literal or binding pattern of a context token, * on the condition that one exists and that the context implies completion should be given. @@ -953,6 +1020,49 @@ namespace ts.Completions { return undefined; } + function isFromClassElementDeclaration(node: Node) { + return isClassElement(node.parent) && isClassLike(node.parent.parent); + } + + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetClassLikeCompletionContainer(contextToken: Node): ClassLikeDeclaration { + if (contextToken) { + switch (contextToken.kind) { + case SyntaxKind.OpenBraceToken: // class c { | + if (isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + + // class c {getValue(): number; | } + case SyntaxKind.CommaToken: + case SyntaxKind.SemicolonToken: + // class c { method() { } | } + case SyntaxKind.CloseBraceToken: + if (isClassLike(location)) { + return location; + } + break; + + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent as ClassLikeDeclaration; + } + } + } + + // class c { method() { } | method2() { } } + if (location && location.kind === SyntaxKind.SyntaxList && isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } + function tryGetContainingJsxElement(contextToken: Node): JsxOpeningLikeElement { if (contextToken) { const parent = contextToken.parent; @@ -1081,7 +1191,7 @@ namespace ts.Completions { isFunction(containingNodeKind); case SyntaxKind.StaticKeyword: - return containingNodeKind === SyntaxKind.PropertyDeclaration; + return containingNodeKind === SyntaxKind.PropertyDeclaration && !isClassLike(contextToken.parent.parent); case SyntaxKind.DotDotDotToken: return containingNodeKind === SyntaxKind.Parameter || @@ -1098,13 +1208,17 @@ namespace ts.Completions { containingNodeKind === SyntaxKind.ExportSpecifier || containingNodeKind === SyntaxKind.NamespaceImport; + case SyntaxKind.GetKeyword: + case SyntaxKind.SetKeyword: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } + // falls through case SyntaxKind.ClassKeyword: case SyntaxKind.EnumKeyword: case SyntaxKind.InterfaceKeyword: case SyntaxKind.FunctionKeyword: case SyntaxKind.VarKeyword: - case SyntaxKind.GetKeyword: - case SyntaxKind.SetKeyword: case SyntaxKind.ImportKeyword: case SyntaxKind.LetKeyword: case SyntaxKind.ConstKeyword: @@ -1113,6 +1227,13 @@ namespace ts.Completions { return true; } + // If the previous token is keyword correspoding to class member completion keyword + // there will be completion available here + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } + // Previous token may have been a keyword that was converted to an identifier. switch (contextToken.getText()) { case "abstract": @@ -1159,7 +1280,7 @@ namespace ts.Completions { for (const element of namedImportsOrExports) { // If this is the current item we are editing right now, do not filter it out - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } @@ -1198,7 +1319,7 @@ namespace ts.Completions { } // If this is the current item we are editing right now, do not filter it out - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } @@ -1214,7 +1335,7 @@ namespace ts.Completions { // TODO(jfreeman): Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. - existingName = (m.name).text; + existingName = (getNameOfDeclaration(m) as Identifier).text; } existingMemberNames.set(existingName, true); @@ -1223,6 +1344,58 @@ namespace ts.Completions { return filter(contextualMemberSymbols, m => !existingMemberNames.get(m.name)); } + /** + * Filters out completion suggestions for class elements. + * + * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags + */ + function filterClassMembersList(baseSymbols: Symbol[], implementingTypeSymbols: Symbol[], existingMembers: ClassElement[], currentClassElementModifierFlags: ModifierFlags): Symbol[] { + const existingMemberNames = createMap(); + for (const m of existingMembers) { + // Ignore omitted expressions for missing members + if (m.kind !== SyntaxKind.PropertyDeclaration && + m.kind !== SyntaxKind.MethodDeclaration && + m.kind !== SyntaxKind.GetAccessor && + m.kind !== SyntaxKind.SetAccessor) { + continue; + } + + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + + // Dont filter member even if the name matches if it is declared private in the list + if (hasModifier(m, ModifierFlags.Private)) { + continue; + } + + // do not filter it out if the static presence doesnt match + const mIsStatic = hasModifier(m, ModifierFlags.Static); + const currentElementIsStatic = !!(currentClassElementModifierFlags & ModifierFlags.Static); + if ((mIsStatic && !currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + + const existingName = getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + + return concatenate( + filter(baseSymbols, baseProperty => isValidProperty(baseProperty, ModifierFlags.Private)), + filter(implementingTypeSymbols, implementingProperty => isValidProperty(implementingProperty, ModifierFlags.NonPublicAccessibilityModifier)) + ); + + function isValidProperty(propertySymbol: Symbol, inValidModifierFlags: ModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } + } + /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. * @@ -1233,7 +1406,7 @@ namespace ts.Completions { const seenNames = createMap(); for (const attr of attributes) { // If this is the current item we are editing right now, do not filter it out - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } @@ -1244,6 +1417,10 @@ namespace ts.Completions { return filter(symbols, a => !seenNames.get(a.name)); } + + function isCurrentlyEditingNode(node: Node): boolean { + return node.getStart() <= position && position <= node.getEnd(); + } } /** @@ -1306,6 +1483,29 @@ namespace ts.Completions { }); } + function isClassMemberCompletionKeyword(kind: SyntaxKind) { + switch (kind) { + case SyntaxKind.PublicKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.AbstractKeyword: + case SyntaxKind.StaticKeyword: + case SyntaxKind.ConstructorKeyword: + case SyntaxKind.ReadonlyKeyword: + case SyntaxKind.GetKeyword: + case SyntaxKind.SetKeyword: + case SyntaxKind.AsyncKeyword: + return true; + } + } + + function isClassMemberCompletionKeywordText(text: string) { + return isClassMemberCompletionKeyword(stringToToken(text)); + } + + const classMemberKeywordCompletions = filter(keywordCompletions, entry => + isClassMemberCompletionKeywordText(entry.name)); + function isEqualityExpression(node: Node): node is BinaryExpression { return isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } diff --git a/src/services/documentHighlights.ts b/src/services/documentHighlights.ts index a8afc46d736..36b72ecfa78 100644 --- a/src/services/documentHighlights.ts +++ b/src/services/documentHighlights.ts @@ -1,8 +1,8 @@ /* @internal */ namespace ts.DocumentHighlights { - export function getDocumentHighlights(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] { - const node = getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + export function getDocumentHighlights(program: Program, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] { + const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } function getHighlightSpanForNode(node: Node, sourceFile: SourceFile): HighlightSpan { @@ -16,8 +16,8 @@ namespace ts.DocumentHighlights { }; } - function getSemanticDocumentHighlights(node: Node, typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] { - const referenceEntries = FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node: Node, program: Program, cancellationToken: CancellationToken, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] { + const referenceEntries = FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index fd717fc546e..efc6a6f6ed1 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -41,14 +41,15 @@ namespace ts.FindAllReferences { readonly implementations?: boolean; } - export function findReferencedSymbols(checker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined { - const referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + export function findReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined { + const referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } const out: ReferencedSymbol[] = []; + const checker = program.getTypeChecker(); for (const { definition, references } of referencedSymbols) { // Only include referenced symbols that have a valid definition. if (definition) { @@ -59,44 +60,51 @@ namespace ts.FindAllReferences { return out; } - export function getImplementationsAtPosition(checker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ImplementationLocation[] { - const node = getTouchingPropertyName(sourceFile, position); - const referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + export function getImplementationsAtPosition(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ImplementationLocation[] { + // A node in a JSDoc comment can't have an implementation anyway. + const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); + const referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + const checker = program.getTypeChecker(); return map(referenceEntries, entry => toImplementationLocation(entry, checker)); } - function getImplementationReferenceEntries(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], node: Node): Entry[] | undefined { + function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], node: Node): Entry[] | undefined { + if (node.kind === SyntaxKind.SourceFile) { + return undefined; + } + + const checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) { const result: NodeEntry[] = []; - Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, node => result.push(nodeEntry(node))); + Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, node => result.push(nodeEntry(node))); return result; } else if (node.kind === SyntaxKind.SuperKeyword || isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" - const symbol = typeChecker.getSymbolAtLocation(node); + const symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - export function findReferencedEntries(checker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number, options?: Options): ReferenceEntry[] | undefined { - const x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + export function findReferencedEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number, options?: Options): ReferenceEntry[] | undefined { + const x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return map(x, toReferenceEntry); } - export function getReferenceEntriesForNode(node: Node, sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, options: Options = {}): Entry[] | undefined { - return flattenEntries(Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + export function getReferenceEntriesForNode(node: Node, program: Program, sourceFiles: SourceFile[], cancellationToken: CancellationToken, options: Options = {}): Entry[] | undefined { + return flattenEntries(Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } - function findAllReferencedSymbols(checker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number, options?: Options): SymbolAndEntries[] | undefined { + function findAllReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number, options?: Options): SymbolAndEntries[] | undefined { const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols: SymbolAndEntries[]): Entry[] { @@ -108,10 +116,6 @@ namespace ts.FindAllReferences { switch (def.type) { case "symbol": { const { symbol, node } = def; - const declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } const { displayParts, kind } = getDefinitionKindAndDisplayParts(symbol, node, checker); const name = displayParts.map(p => p.text).join(""); return { node, name, kind, displayParts }; @@ -146,7 +150,7 @@ namespace ts.FindAllReferences { const { node, name, kind, displayParts } = info; const sourceFile = node.getSourceFile(); return { - containerKind: "", + containerKind: ScriptElementKind.unknown, containerName: "", fileName: sourceFile.fileName, kind, @@ -156,7 +160,7 @@ namespace ts.FindAllReferences { }; } - function getDefinitionKindAndDisplayParts(symbol: Symbol, node: Node, checker: TypeChecker): { displayParts: SymbolDisplayPart[], kind: string } { + function getDefinitionKindAndDisplayParts(symbol: Symbol, node: Node, checker: TypeChecker): { displayParts: SymbolDisplayPart[], kind: ScriptElementKind } { const { displayParts, symbolKind } = SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), getContainerNode(node), node); return { displayParts, kind: symbolKind }; @@ -172,7 +176,7 @@ namespace ts.FindAllReferences { fileName: node.getSourceFile().fileName, textSpan: getTextSpan(node), isWriteAccess: isWriteAccess(node), - isDefinition: isDeclarationName(node) || isLiteralComputedPropertyDeclarationName(node), + isDefinition: isAnyDeclarationName(node) || isLiteralComputedPropertyDeclarationName(node), isInString }; } @@ -187,7 +191,7 @@ namespace ts.FindAllReferences { } } - function implementationKindDisplayParts(node: ts.Node, checker: ts.TypeChecker): { kind: string, displayParts: SymbolDisplayPart[] } { + function implementationKindDisplayParts(node: ts.Node, checker: ts.TypeChecker): { kind: ScriptElementKind, displayParts: SymbolDisplayPart[] } { const symbol = checker.getSymbolAtLocation(isDeclaration(node) && node.name ? node.name : node); if (symbol) { return getDefinitionKindAndDisplayParts(symbol, node, checker); @@ -238,22 +242,20 @@ namespace ts.FindAllReferences { /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccess(node: Node): boolean { - if (node.kind === SyntaxKind.Identifier && isDeclarationName(node)) { + if (isAnyDeclarationName(node)) { return true; } - const parent = node.parent; - if (parent) { - if (parent.kind === SyntaxKind.PostfixUnaryExpression || parent.kind === SyntaxKind.PrefixUnaryExpression) { + const { parent } = node; + switch (parent && parent.kind) { + case SyntaxKind.PostfixUnaryExpression: + case SyntaxKind.PrefixUnaryExpression: return true; - } - else if (parent.kind === SyntaxKind.BinaryExpression && (parent).left === node) { - const operator = (parent).operatorToken.kind; - return SyntaxKind.FirstAssignment <= operator && operator <= SyntaxKind.LastAssignment; - } + case SyntaxKind.BinaryExpression: + return (parent).left === node && isAssignmentOperator((parent).operatorToken.kind); + default: + return false; } - - return false; } } @@ -261,7 +263,7 @@ namespace ts.FindAllReferences { /* @internal */ namespace ts.FindAllReferences.Core { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - export function getReferencedSymbolsForNode(node: Node, sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, options: Options = {}): SymbolAndEntries[] | undefined { + export function getReferencedSymbolsForNode(node: Node, program: Program, sourceFiles: SourceFile[], cancellationToken: CancellationToken, options: Options = {}): SymbolAndEntries[] | undefined { if (node.kind === ts.SyntaxKind.SourceFile) { return undefined; } @@ -273,6 +275,7 @@ namespace ts.FindAllReferences.Core { } } + const checker = program.getTypeChecker(); const symbol = checker.getSymbolAtLocation(node); // Could not find a symbol e.g. unknown identifier @@ -285,14 +288,65 @@ namespace ts.FindAllReferences.Core { return undefined; } - // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; + if (symbol.flags & SymbolFlags.Module && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } + function isModuleReferenceLocation(node: ts.Node): boolean { + if (node.kind !== SyntaxKind.StringLiteral) { + return false; + } + switch (node.parent.kind) { + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.ExternalModuleReference: + case SyntaxKind.ImportDeclaration: + case SyntaxKind.ExportDeclaration: + return true; + case SyntaxKind.CallExpression: + return isRequireCall(node.parent as CallExpression, /*checkArgumentIsStringLiteral*/ false); + default: + return false; + } + } + + function getReferencedSymbolsForModule(program: Program, symbol: Symbol, sourceFiles: SourceFile[]): SymbolAndEntries[] { + Debug.assert(!!symbol.valueDeclaration); + + const references = findModuleReferences(program, sourceFiles, symbol).map(reference => { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: createTextSpanFromRange(reference.ref), + }; + } + }); + + for (const decl of symbol.declarations) { + switch (decl.kind) { + case ts.SyntaxKind.SourceFile: + // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) + break; + case ts.SyntaxKind.ModuleDeclaration: + references.push({ type: "node", node: (decl as ts.ModuleDeclaration).name }); + break; + default: + Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + + return [{ + definition: { type: "symbol", symbol, node: symbol.valueDeclaration }, + references + }]; + } + /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node: Node, sourceFiles: SourceFile[], cancellationToken: CancellationToken): SymbolAndEntries[] | undefined { if (isTypeKeyword(node.kind)) { @@ -559,7 +613,7 @@ namespace ts.FindAllReferences.Core { } function isObjectBindingPatternElementWithoutPropertyName(symbol: Symbol): boolean { - const bindingElement = getDeclarationOfKind(symbol, SyntaxKind.BindingElement); + const bindingElement = getDeclarationOfKind(symbol, SyntaxKind.BindingElement); return bindingElement && bindingElement.parent.kind === SyntaxKind.ObjectBindingPattern && !bindingElement.propertyName; @@ -567,7 +621,7 @@ namespace ts.FindAllReferences.Core { function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol: Symbol, checker: TypeChecker): Symbol | undefined { if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - const bindingElement = getDeclarationOfKind(symbol, SyntaxKind.BindingElement); + const bindingElement = getDeclarationOfKind(symbol, SyntaxKind.BindingElement); const typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); return typeOfPattern && checker.getPropertyOfType(typeOfPattern, (bindingElement.name).text); } @@ -646,7 +700,9 @@ namespace ts.FindAllReferences.Core { return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile: SourceFile, symbolName: string, start: number, end: number): number[] { + function getPossibleSymbolReferencePositions(sourceFile: SourceFile, symbolName: string, container: Node = sourceFile, fullStart = false): number[] { + const start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + const end = container.getEnd(); const positions: number[] = []; /// TODO: Cache symbol existence for files to save text search @@ -685,16 +741,11 @@ namespace ts.FindAllReferences.Core { const references: Entry[] = []; const sourceFile = container.getSourceFile(); const labelName = targetLabel.text; - const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (const position of possiblePositions) { - const node = getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } - + const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); // Only pick labels that are either the target label, or have a target that is the target label - if (node === targetLabel || - (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel)) { + if (node && (node === targetLabel || (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel))) { references.push(nodeEntry(node)); } } @@ -706,15 +757,14 @@ namespace ts.FindAllReferences.Core { // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node && node.kind) { case SyntaxKind.Identifier: - return node.getWidth() === searchSymbolName.length; + return unescapeIdentifier((node as Identifier).text).length === searchSymbolName.length; case SyntaxKind.StringLiteral: return (isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - // For string literals we have two additional chars for the quotes - node.getWidth() === searchSymbolName.length + 2; + (node as StringLiteral).text.length === searchSymbolName.length; case SyntaxKind.NumericLiteral: - return isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && (node as NumericLiteral).text.length === searchSymbolName.length; default: return false; @@ -731,9 +781,10 @@ namespace ts.FindAllReferences.Core { } function addReferencesForKeywordInFile(sourceFile: SourceFile, kind: SyntaxKind, searchText: string, references: Push): void { - const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + // Want fullStart so we can find the symbol in JSDoc comments + const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile, /*fullStart*/ true); for (const position of possiblePositions) { - const referenceLocation = getTouchingPropertyName(sourceFile, position); + const referenceLocation = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (referenceLocation.kind === kind) { references.push(nodeEntry(referenceLocation)); } @@ -755,15 +806,13 @@ namespace ts.FindAllReferences.Core { return; } - const start = state.findInComments ? container.getFullStart() : container.getStart(); - const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (const position of possiblePositions) { + for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments || container.jsDoc !== undefined)) { getReferencesAtLocation(sourceFile, position, search, state); } } function getReferencesAtLocation(sourceFile: SourceFile, position: number, search: Search, state: State): void { - const referenceLocation = getTouchingPropertyName(sourceFile, position); + const referenceLocation = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (!isValidReferencePosition(referenceLocation, search.text)) { // This wasn't the start of a token. Check to see if it might be a @@ -908,7 +957,7 @@ namespace ts.FindAllReferences.Core { * position of property accessing, the referenceEntry of such position will be handled in the first case. */ if (!(flags & SymbolFlags.Transient) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } @@ -1201,9 +1250,9 @@ namespace ts.FindAllReferences.Core { const references: Entry[] = []; const sourceFile = searchSpaceNode.getSourceFile(); - const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); for (const position of possiblePositions) { - const node = getTouchingWord(sourceFile, position); + const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || node.kind !== SyntaxKind.SuperKeyword) { continue; @@ -1263,13 +1312,13 @@ namespace ts.FindAllReferences.Core { if (searchSpaceNode.kind === SyntaxKind.SourceFile) { forEach(sourceFiles, sourceFile => { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { const sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } @@ -1280,7 +1329,7 @@ namespace ts.FindAllReferences.Core { function getThisReferencesInFile(sourceFile: SourceFile, searchSpaceNode: Node, possiblePositions: number[], result: Entry[]): void { forEach(possiblePositions, position => { - const node = getTouchingWord(sourceFile, position); + const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || !isThis(node)) { return; } @@ -1323,7 +1372,7 @@ namespace ts.FindAllReferences.Core { for (const sourceFile of sourceFiles) { cancellationToken.throwIfCancellationRequested(); - const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } @@ -1334,7 +1383,7 @@ namespace ts.FindAllReferences.Core { function getReferencesForStringLiteralInFile(sourceFile: SourceFile, searchText: string, possiblePositions: number[], references: Push): void { for (const position of possiblePositions) { - const node = getTouchingWord(sourceFile, position); + const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (node && node.kind === SyntaxKind.StringLiteral && (node as StringLiteral).text === searchText) { references.push(nodeEntry(node, /*isInString*/ true)); } diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 5c2171cc4ae..531b768f6d8 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -487,7 +487,7 @@ namespace ts.formatting { // falls through case SyntaxKind.PropertyDeclaration: case SyntaxKind.Parameter: - return (node).name.kind; + return getNameOfDeclaration(node).kind; } } @@ -599,7 +599,7 @@ namespace ts.formatting { child => { processChildNode(child, /*inheritedIndentation*/ Constants.Unknown, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); }, - (nodes: NodeArray) => { + nodes => { processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); }); diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 01feaf39081..18b0479c85a 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -341,10 +341,7 @@ namespace ts.formatting { return Value.Unknown; } - if (node.parent && ( - node.parent.kind === SyntaxKind.CallExpression || - node.parent.kind === SyntaxKind.NewExpression) && - (node.parent).expression !== node) { + if (node.parent && isCallOrNewExpression(node.parent) && (node.parent).expression !== node) { const fullCallOrNewExpression = (node.parent).expression; const startingExpression = getStartingExpression(fullCallOrNewExpression); diff --git a/src/services/formatting/tokenRange.ts b/src/services/formatting/tokenRange.ts index 28f22cec475..29855279e25 100644 --- a/src/services/formatting/tokenRange.ts +++ b/src/services/formatting/tokenRange.ts @@ -3,23 +3,13 @@ /* @internal */ namespace ts.formatting { export namespace Shared { - export interface ITokenAccess { - GetTokens(): SyntaxKind[]; - Contains(token: SyntaxKind): boolean; - isSpecific(): boolean; + const allTokens: SyntaxKind[] = []; + for (let token = SyntaxKind.FirstToken; token <= SyntaxKind.LastToken; token++) { + allTokens.push(token); } - export class TokenRangeAccess implements ITokenAccess { - private tokens: SyntaxKind[]; - - constructor(from: SyntaxKind, to: SyntaxKind, except: SyntaxKind[]) { - this.tokens = []; - for (let token = from; token <= to; token++) { - if (ts.indexOf(except, token) < 0) { - this.tokens.push(token); - } - } - } + class TokenValuesAccess implements TokenRange { + constructor(private readonly tokens: SyntaxKind[] = []) { } public GetTokens(): SyntaxKind[] { return this.tokens; @@ -32,27 +22,8 @@ namespace ts.formatting { public isSpecific() { return true; } } - export class TokenValuesAccess implements ITokenAccess { - private tokens: SyntaxKind[]; - - constructor(tks: SyntaxKind[]) { - this.tokens = tks && tks.length ? tks : []; - } - - public GetTokens(): SyntaxKind[] { - return this.tokens; - } - - public Contains(token: SyntaxKind): boolean { - return this.tokens.indexOf(token) >= 0; - } - - public isSpecific() { return true; } - } - - export class TokenSingleValueAccess implements ITokenAccess { - constructor(public token: SyntaxKind) { - } + class TokenSingleValueAccess implements TokenRange { + constructor(private readonly token: SyntaxKind) {} public GetTokens(): SyntaxKind[] { return [this.token]; @@ -65,12 +36,7 @@ namespace ts.formatting { public isSpecific() { return true; } } - const allTokens: SyntaxKind[] = []; - for (let token = SyntaxKind.FirstToken; token <= SyntaxKind.LastToken; token++) { - allTokens.push(token); - } - - export class TokenAllAccess implements ITokenAccess { + class TokenAllAccess implements TokenRange { public GetTokens(): SyntaxKind[] { return allTokens; } @@ -86,8 +52,8 @@ namespace ts.formatting { public isSpecific() { return false; } } - export class TokenAllExceptAccess implements ITokenAccess { - constructor(readonly except: SyntaxKind) {} + class TokenAllExceptAccess implements TokenRange { + constructor(private readonly except: SyntaxKind) {} public GetTokens(): SyntaxKind[] { return allTokens.filter(t => t !== this.except); @@ -100,55 +66,58 @@ namespace ts.formatting { public isSpecific() { return false; } } - export class TokenRange { - constructor(public tokenAccess: ITokenAccess) { + export interface TokenRange { + GetTokens(): SyntaxKind[]; + Contains(token: SyntaxKind): boolean; + isSpecific(): boolean; + } + + export namespace TokenRange { + export function FromToken(token: SyntaxKind): TokenRange { + return new TokenSingleValueAccess(token); } - static FromToken(token: SyntaxKind): TokenRange { - return new TokenRange(new TokenSingleValueAccess(token)); + export function FromTokens(tokens: SyntaxKind[]): TokenRange { + return new TokenValuesAccess(tokens); } - static FromTokens(tokens: SyntaxKind[]): TokenRange { - return new TokenRange(new TokenValuesAccess(tokens)); + export function FromRange(from: SyntaxKind, to: SyntaxKind, except: SyntaxKind[] = []): TokenRange { + const tokens: SyntaxKind[] = []; + for (let token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); } - static FromRange(f: SyntaxKind, to: SyntaxKind, except: SyntaxKind[] = []): TokenRange { - return new TokenRange(new TokenRangeAccess(f, to, except)); + export function AnyExcept(token: SyntaxKind): TokenRange { + return new TokenAllExceptAccess(token); } - static AnyExcept(token: SyntaxKind): TokenRange { - return new TokenRange(new TokenAllExceptAccess(token)); - } - - public GetTokens(): SyntaxKind[] { - return this.tokenAccess.GetTokens(); - } - - public Contains(token: SyntaxKind): boolean { - return this.tokenAccess.Contains(token); - } - - public toString(): string { - return this.tokenAccess.toString(); - } - - public isSpecific() { - return this.tokenAccess.isSpecific(); - } - - static Any: TokenRange = new TokenRange(new TokenAllAccess()); - static AnyIncludingMultilineComments = TokenRange.FromTokens([...allTokens, SyntaxKind.MultiLineCommentTrivia]); - static Keywords = TokenRange.FromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword); - static BinaryOperators = TokenRange.FromRange(SyntaxKind.FirstBinaryOperator, SyntaxKind.LastBinaryOperator); - static BinaryKeywordOperators = TokenRange.FromTokens([SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.AsKeyword, SyntaxKind.IsKeyword]); - static UnaryPrefixOperators = TokenRange.FromTokens([SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]); - static UnaryPrefixExpressions = TokenRange.FromTokens([SyntaxKind.NumericLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); - static UnaryPreincrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); - static UnaryPostincrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]); - static UnaryPredecrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); - static UnaryPostdecrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]); - static Comments = TokenRange.FromTokens([SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia]); - static TypeNames = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.NumberKeyword, SyntaxKind.StringKeyword, SyntaxKind.BooleanKeyword, SyntaxKind.SymbolKeyword, SyntaxKind.VoidKeyword, SyntaxKind.AnyKeyword]); + export const Any: TokenRange = new TokenAllAccess(); + export const AnyIncludingMultilineComments = TokenRange.FromTokens([...allTokens, SyntaxKind.MultiLineCommentTrivia]); + export const Keywords = TokenRange.FromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword); + export const BinaryOperators = TokenRange.FromRange(SyntaxKind.FirstBinaryOperator, SyntaxKind.LastBinaryOperator); + export const BinaryKeywordOperators = TokenRange.FromTokens([ + SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.AsKeyword, SyntaxKind.IsKeyword]); + export const UnaryPrefixOperators = TokenRange.FromTokens([ + SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]); + export const UnaryPrefixExpressions = TokenRange.FromTokens([ + SyntaxKind.NumericLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, + SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); + export const UnaryPreincrementExpressions = TokenRange.FromTokens([ + SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); + export const UnaryPostincrementExpressions = TokenRange.FromTokens([ + SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]); + export const UnaryPredecrementExpressions = TokenRange.FromTokens([ + SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); + export const UnaryPostdecrementExpressions = TokenRange.FromTokens([ + SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]); + export const Comments = TokenRange.FromTokens([SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia]); + export const TypeNames = TokenRange.FromTokens([ + SyntaxKind.Identifier, SyntaxKind.NumberKeyword, SyntaxKind.StringKeyword, SyntaxKind.BooleanKeyword, + SyntaxKind.SymbolKeyword, SyntaxKind.VoidKeyword, SyntaxKind.AnyKeyword]); } } } diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index f2602903be3..9b96f339bf6 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -19,7 +19,7 @@ namespace ts.GoToDefinition { [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } - const node = getTouchingPropertyName(sourceFile, position); + const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -50,19 +50,10 @@ namespace ts.GoToDefinition { // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. - if (symbol.flags & SymbolFlags.Alias) { - const declaration = symbol.declarations[0]; - - // Go to the original declaration for cases: - // - // (1) when the aliased symbol was declared in the location(parent). - // (2) when the aliased symbol is originating from a named import. - // - if (node.kind === SyntaxKind.Identifier && - (node.parent === declaration || - (declaration.kind === SyntaxKind.ImportSpecifier && declaration.parent && declaration.parent.kind === SyntaxKind.NamedImports))) { - - symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.flags & SymbolFlags.Alias && shouldSkipAlias(node, symbol.declarations[0])) { + const aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; } } @@ -85,17 +76,6 @@ namespace ts.GoToDefinition { declaration => createDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName)); } - if (isJsxOpeningLikeElement(node.parent)) { - // If there are errors when trying to figure out stateless component function, just return the first declaration - // For example: - // declare function /*firstSource*/MainButton(buttonProps: ButtonProps): JSX.Element; - // declare function /*secondSource*/MainButton(linkProps: LinkProps): JSX.Element; - // declare function /*thirdSource*/MainButton(props: ButtonProps | LinkProps): JSX.Element; - // let opt =
; // Error - We get undefined for resolved signature indicating an error, then just return the first declaration - const {symbolName, symbolKind, containerName} = getSymbolInfo(typeChecker, symbol, node); - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } - // If the current location we want to find its definition is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. // For example @@ -106,22 +86,16 @@ namespace ts.GoToDefinition { // function Foo(arg: Props) {} // Foo( { pr/*1*/op1: 10, prop2: true }) const element = getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent as Expression)) { - const result: DefinitionInfo[] = []; - const propertySymbols = getPropertySymbolsFromContextualType(typeChecker, element); - for (const propertySymbol of propertySymbols) { - result.push(...getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent as Expression)) { + return flatMap(getPropertySymbolsFromContextualType(typeChecker, element), propertySymbol => + getDefinitionFromSymbol(typeChecker, propertySymbol, node)); } return getDefinitionFromSymbol(typeChecker, symbol, node); } /// Goto type export function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): DefinitionInfo[] { - const node = getTouchingPropertyName(sourceFile, position); + const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -153,6 +127,29 @@ namespace ts.GoToDefinition { return getDefinitionFromSymbol(typeChecker, type.symbol, node); } + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from an import. + // + function shouldSkipAlias(node: Node, declaration: Node): boolean { + if (node.kind !== SyntaxKind.Identifier) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case SyntaxKind.ImportClause: + case SyntaxKind.ImportEqualsDeclaration: + return true; + case SyntaxKind.ImportSpecifier: + return declaration.parent.kind === SyntaxKind.NamedImports; + default: + return false; + } + } + function getDefinitionFromSymbol(typeChecker: TypeChecker, symbol: Symbol, node: Node): DefinitionInfo[] { const result: DefinitionInfo[] = []; const declarations = symbol.getDeclarations(); @@ -168,7 +165,7 @@ namespace ts.GoToDefinition { return result; - function tryAddConstructSignature(symbol: Symbol, location: Node, symbolKind: string, symbolName: string, containerName: string, result: DefinitionInfo[]) { + function tryAddConstructSignature(symbol: Symbol, location: Node, symbolKind: ScriptElementKind, symbolName: string, containerName: string, result: DefinitionInfo[]) { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class if (isNewExpressionTarget(location) || location.kind === SyntaxKind.ConstructorKeyword) { @@ -176,12 +173,8 @@ namespace ts.GoToDefinition { // Find the first class-like declaration and try to get the construct signature. for (const declaration of symbol.getDeclarations()) { if (isClassLike(declaration)) { - return tryAddSignature(declaration.members, - /*selectConstructors*/ true, - symbolKind, - symbolName, - containerName, - result); + return tryAddSignature( + declaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); } } @@ -191,14 +184,14 @@ namespace ts.GoToDefinition { return false; } - function tryAddCallSignature(symbol: Symbol, location: Node, symbolKind: string, symbolName: string, containerName: string, result: DefinitionInfo[]) { + function tryAddCallSignature(symbol: Symbol, location: Node, symbolKind: ScriptElementKind, symbolName: string, containerName: string, result: DefinitionInfo[]) { if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) { return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); } return false; } - function tryAddSignature(signatureDeclarations: Declaration[] | undefined, selectConstructors: boolean, symbolKind: string, symbolName: string, containerName: string, result: DefinitionInfo[]) { + function tryAddSignature(signatureDeclarations: Declaration[] | undefined, selectConstructors: boolean, symbolKind: ScriptElementKind, symbolName: string, containerName: string, result: DefinitionInfo[]) { if (!signatureDeclarations) { return false; } @@ -234,12 +227,12 @@ namespace ts.GoToDefinition { } /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ - function createDefinitionInfo(node: Declaration, symbolKind: string, symbolName: string, containerName: string): DefinitionInfo { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + function createDefinitionInfo(node: Declaration, symbolKind: ScriptElementKind, symbolName: string, containerName: string): DefinitionInfo { + return createDefinitionInfoFromName(getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ - function createDefinitionInfoFromName(name: Node, symbolKind: string, symbolName: string, containerName: string): DefinitionInfo { + function createDefinitionInfoFromName(name: Node, symbolKind: ScriptElementKind, symbolName: string, containerName: string): DefinitionInfo { const sourceFile = name.getSourceFile(); return { fileName: sourceFile.fileName, @@ -266,7 +259,7 @@ namespace ts.GoToDefinition { function findReferenceInPosition(refs: FileReference[], pos: number): FileReference { for (const ref of refs) { - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index c94d5cc3143..f20c80c14ef 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -300,6 +300,40 @@ namespace ts.FindAllReferences { }); } + export type ModuleReference = + /** "import" also includes require() calls. */ + | { kind: "import", literal: StringLiteral } + /** or */ + | { kind: "reference", referencingFile: SourceFile, ref: FileReference }; + export function findModuleReferences(program: Program, sourceFiles: SourceFile[], searchModuleSymbol: Symbol): ModuleReference[] { + const refs: ModuleReference[] = []; + const checker = program.getTypeChecker(); + for (const referencingFile of sourceFiles) { + const searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === ts.SyntaxKind.SourceFile) { + for (const ref of referencingFile.referencedFiles) { + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile, ref }); + } + } + for (const ref of referencingFile.typeReferenceDirectives) { + const referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === (searchSourceFile as ts.SourceFile).fileName) { + refs.push({ kind: "reference", referencingFile, ref }); + } + } + } + + forEachImport(referencingFile, (_importDecl, moduleSpecifier) => { + const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken): Map { const map = createMap(); @@ -330,7 +364,7 @@ namespace ts.FindAllReferences { /** Calls `action` for each import, re-export, or require() in a file. */ function forEachImport(sourceFile: SourceFile, action: (importStatement: ImporterOrCallExpression, imported: StringLiteral) => void): void { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (const moduleSpecifier of sourceFile.imports) { action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); } @@ -358,27 +392,21 @@ namespace ts.FindAllReferences { } } }); - - if (sourceFile.flags & NodeFlags.JavaScriptFile) { - // Find all 'require()' calls. - sourceFile.forEachChild(function recur(node: Node): void { - if (isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - action(node, node.arguments[0] as StringLiteral); - } else { - node.forEachChild(recur); - } - }); - } } } - function importerFromModuleSpecifier(moduleSpecifier: StringLiteral): Importer { + function importerFromModuleSpecifier(moduleSpecifier: StringLiteral): ImporterOrCallExpression { const decl = moduleSpecifier.parent; - if (decl.kind === SyntaxKind.ImportDeclaration || decl.kind === SyntaxKind.ExportDeclaration) { - return decl as ImportDeclaration | ExportDeclaration; + switch (decl.kind) { + case SyntaxKind.CallExpression: + case SyntaxKind.ImportDeclaration: + case SyntaxKind.ExportDeclaration: + return decl as ImportDeclaration | ExportDeclaration | CallExpression; + case SyntaxKind.ExternalModuleReference: + return (decl as ExternalModuleReference).parent; + default: + Debug.fail(`Unexpected module specifier parent: ${decl.kind}`); } - Debug.assert(decl.kind === SyntaxKind.ExternalModuleReference); - return (decl as ExternalModuleReference).parent; } export interface ImportedSymbol { @@ -532,14 +560,18 @@ namespace ts.FindAllReferences { return isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol, exportKind } : undefined; } - function symbolName(symbol: Symbol): string { + function symbolName(symbol: Symbol): string | undefined { if (symbol.name !== "default") { return symbol.name; } - const name = forEach(symbol.declarations, ({ name }) => name && name.kind === SyntaxKind.Identifier && name.text); - Debug.assert(!!name); - return name; + return forEach(symbol.declarations, decl => { + if (isExportAssignment(decl)) { + return isIdentifier(decl.expression) ? decl.expression.text : undefined; + } + const name = getNameOfDeclaration(decl); + return name && name.kind === SyntaxKind.Identifier && name.text; + }); } /** If at an export specifier, go to the symbol it refers to. */ diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index 37c22b4352c..8ca55029603 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -28,6 +28,7 @@ namespace ts.JsDoc { "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -38,14 +39,12 @@ namespace ts.JsDoc { "throws", "type", "typedef", - "property", - "prop", "version" ]; let jsDocTagNameCompletionEntries: CompletionEntry[]; let jsDocTagCompletionEntries: CompletionEntry[]; - export function getJsDocCommentsFromDeclarations(declarations: Declaration[]) { + export function getJsDocCommentsFromDeclarations(declarations?: Declaration[]) { // Only collect doc comments from duplicate declarations once: // In case of a union property there might be same declaration multiple times // which only varies in type parameter @@ -70,7 +69,7 @@ namespace ts.JsDoc { return documentationComment; } - export function getJsDocTagsFromDeclarations(declarations: Declaration[]) { + export function getJsDocTagsFromDeclarations(declarations?: Declaration[]) { // Only collect doc comments from duplicate declarations once. const tags: JSDocTagInfo[] = []; forEachUnique(declarations, declaration => { @@ -159,7 +158,7 @@ namespace ts.JsDoc { return undefined; } - const tokenAtPos = getTokenAtPosition(sourceFile, position); + const tokenAtPos = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); const tokenStart = tokenAtPos.getStart(); if (!tokenAtPos || tokenStart < position) { return undefined; diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 2c8d43b535b..d4adeaea974 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -52,7 +52,7 @@ namespace ts.NavigateTo { rawItems = filter(rawItems, item => { const decl = item.declaration; if (decl.kind === SyntaxKind.ImportClause || decl.kind === SyntaxKind.ImportSpecifier || decl.kind === SyntaxKind.ImportEqualsDeclaration) { - const importer = checker.getSymbolAtLocation(decl.name); + const importer = checker.getSymbolAtLocation((decl as NamedDeclaration).name); const imported = checker.getAliasedSymbol(importer); return importer.name !== imported.name; } @@ -97,17 +97,20 @@ namespace ts.NavigateTo { } function tryAddSingleDeclarationName(declaration: Declaration, containers: string[]) { - if (declaration && declaration.name) { - const text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === SyntaxKind.ComputedPropertyName) { - return tryAddComputedPropertyName((declaration.name).expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; + if (declaration) { + const name = getNameOfDeclaration(declaration); + if (name) { + const text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === SyntaxKind.ComputedPropertyName) { + return tryAddComputedPropertyName((name).expression, containers, /*includeLastPortion*/ true); + } + else { + // Don't know how to add this. + return false; + } } } @@ -143,8 +146,9 @@ namespace ts.NavigateTo { // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === SyntaxKind.ComputedPropertyName) { - if (!tryAddComputedPropertyName((declaration.name).expression, containers, /*includeLastPortion*/ false)) { + const name = getNameOfDeclaration(declaration); + if (name.kind === SyntaxKind.ComputedPropertyName) { + if (!tryAddComputedPropertyName((name).expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -190,6 +194,7 @@ namespace ts.NavigateTo { function createNavigateToItem(rawItem: RawNavigateToItem): NavigateToItem { const declaration = rawItem.declaration; const container = getContainerNode(declaration); + const containerName = container && getNameOfDeclaration(container); return { name: rawItem.name, kind: getNodeKind(declaration), @@ -199,9 +204,9 @@ namespace ts.NavigateTo { fileName: rawItem.fileName, textSpan: createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: container && container.name ? (container.name).text : "", - containerKind: container && container.name ? getNodeKind(container) : "" + containerName: containerName ? (containerName).text : "", + containerKind: containerName ? getNodeKind(container) : ScriptElementKind.unknown }; } } -} \ No newline at end of file +} diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 7a2508fcfd6..819202ff6f4 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -279,8 +279,8 @@ namespace ts.NavigationBar { function mergeChildren(children: NavigationBarNode[]): void { const nameToItems = createMap(); filterMutate(children, child => { - const decl = child.node; - const name = decl.name && nodeText(decl.name); + const declName = getNameOfDeclaration(child.node); + const name = declName && nodeText(declName); if (!name) { // Anonymous items are never merged. return true; @@ -378,9 +378,9 @@ namespace ts.NavigationBar { return getModuleName(node); } - const decl = node; - if (decl.name) { - return getPropertyNameForPropertyNameNode(decl.name); + const declName = getNameOfDeclaration(node); + if (declName) { + return getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case SyntaxKind.FunctionExpression: @@ -399,7 +399,7 @@ namespace ts.NavigationBar { return getModuleName(node); } - const name = (node).name; + const name = getNameOfDeclaration(node); if (name) { const text = nodeText(name); if (text.length > 0) { diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index 2b45457c147..3ded126ab65 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -245,18 +245,15 @@ namespace ts.Completions.PathCompletions { // Get modules that the type checker picked up const ambientModules = map(typeChecker.getAmbientModules(), sym => stripQuotes(sym.name)); - let nonRelativeModules = filter(ambientModules, moduleName => startsWith(moduleName, fragment)); + let nonRelativeModuleNames = filter(ambientModules, moduleName => startsWith(moduleName, fragment)); // Nested modules of the form "module-name/sub" need to be adjusted to only return the string // after the last '/' that appears in the fragment because that's where the replacement span // starts if (isNestedModule) { const moduleNameWithSeperator = ensureTrailingDirectorySeparator(moduleNameFragment); - nonRelativeModules = map(nonRelativeModules, moduleName => { - if (startsWith(fragment, moduleNameWithSeperator)) { - return moduleName.substr(moduleNameWithSeperator.length); - } - return moduleName; + nonRelativeModuleNames = map(nonRelativeModuleNames, nonRelativeModuleName => { + return removePrefix(nonRelativeModuleName, moduleNameWithSeperator); }); } @@ -264,7 +261,7 @@ namespace ts.Completions.PathCompletions { if (!options.moduleResolution || options.moduleResolution === ModuleResolutionKind.NodeJs) { for (const visibleModule of enumerateNodeModulesVisibleToScript(host, scriptPath)) { if (!isNestedModule) { - nonRelativeModules.push(visibleModule.moduleName); + nonRelativeModuleNames.push(visibleModule.moduleName); } else if (startsWith(visibleModule.moduleName, moduleNameFragment)) { const nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, supportedTypeScriptExtensions, /*exclude*/ undefined, /*include*/ ["./*"]); @@ -272,18 +269,18 @@ namespace ts.Completions.PathCompletions { for (let f of nestedFiles) { f = normalizePath(f); const nestedModule = removeFileExtension(getBaseFileName(f)); - nonRelativeModules.push(nestedModule); + nonRelativeModuleNames.push(nestedModule); } } } } } - return deduplicate(nonRelativeModules); + return deduplicate(nonRelativeModuleNames); } export function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): CompletionInfo { - const token = getTokenAtPosition(sourceFile, position); + const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (!token) { return undefined; } @@ -458,7 +455,7 @@ namespace ts.Completions.PathCompletions { } } - function createCompletionEntryForModule(name: string, kind: string, replacementSpan: TextSpan): CompletionEntry { + function createCompletionEntryForModule(name: string, kind: ScriptElementKind, replacementSpan: TextSpan): CompletionEntry { return { name, kind, kindModifiers: ScriptElementKindModifier.none, sortText: name, replacementSpan }; } diff --git a/src/services/refactorProvider.ts b/src/services/refactorProvider.ts new file mode 100644 index 00000000000..0b6ea3487ec --- /dev/null +++ b/src/services/refactorProvider.ts @@ -0,0 +1,69 @@ +/* @internal */ +namespace ts { + export interface Refactor { + /** An unique code associated with each refactor */ + name: string; + + /** Description of the refactor to display in the UI of the editor */ + description: string; + + /** Compute the associated code actions */ + getCodeActions(context: RefactorContext): CodeAction[]; + + /** A fast syntactic check to see if the refactor is applicable at given position. */ + isApplicable(context: RefactorContext): boolean; + } + + export interface RefactorContext { + file: SourceFile; + startPosition: number; + endPosition?: number; + program: Program; + newLineCharacter: string; + rulesProvider?: formatting.RulesProvider; + cancellationToken?: CancellationToken; + } + + export namespace refactor { + // A map with the refactor code as key, the refactor itself as value + // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want + const refactors: Map = createMap(); + + export function registerRefactor(refactor: Refactor) { + refactors.set(refactor.name, refactor); + } + + export function getApplicableRefactors(context: RefactorContext): ApplicableRefactorInfo[] | undefined { + + let results: ApplicableRefactorInfo[]; + const refactorList: Refactor[] = []; + refactors.forEach(refactor => { + refactorList.push(refactor); + }); + for (const refactor of refactorList) { + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor.isApplicable(context)) { + (results || (results = [])).push({ name: refactor.name, description: refactor.description }); + } + } + return results; + } + + export function getRefactorCodeActions(context: RefactorContext, refactorName: string): CodeAction[] | undefined { + + let result: CodeAction[]; + const refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + + const codeActions = refactor.getCodeActions(context); + if (codeActions) { + addRange((result || (result = [])), codeActions); + } + return result; + } + } +} diff --git a/src/services/refactors/convertFunctionToEs6Class.ts b/src/services/refactors/convertFunctionToEs6Class.ts new file mode 100644 index 00000000000..a34e0ccca2f --- /dev/null +++ b/src/services/refactors/convertFunctionToEs6Class.ts @@ -0,0 +1,209 @@ +/* @internal */ + +namespace ts.refactor { + const convertFunctionToES6Class: Refactor = { + name: "Convert to ES2015 class", + description: Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions, + isApplicable + }; + + registerRefactor(convertFunctionToES6Class); + + function isApplicable(context: RefactorContext): boolean { + const start = context.startPosition; + const node = getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false); + const checker = context.program.getTypeChecker(); + let symbol = checker.getSymbolAtLocation(node); + + if (symbol && isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = (symbol.valueDeclaration as VariableDeclaration).initializer.symbol; + } + + return symbol && symbol.flags & SymbolFlags.Function && symbol.members && symbol.members.size > 0; + } + + function getCodeActions(context: RefactorContext): CodeAction[] | undefined { + const start = context.startPosition; + const sourceFile = context.file; + const checker = context.program.getTypeChecker(); + const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + const ctorSymbol = checker.getSymbolAtLocation(token); + const newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + + const deletedNodes: Node[] = []; + const deletes: (() => any)[] = []; + + if (!(ctorSymbol.flags & (SymbolFlags.Function | SymbolFlags.Variable))) { + return []; + } + + const ctorDeclaration = ctorSymbol.valueDeclaration; + const changeTracker = textChanges.ChangeTracker.fromCodeFixContext(context as { newLineCharacter: string, rulesProvider: formatting.RulesProvider }); + + let precedingNode: Node; + let newClassDeclaration: ClassDeclaration; + switch (ctorDeclaration.kind) { + case SyntaxKind.FunctionDeclaration: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration as FunctionDeclaration); + break; + + case SyntaxKind.VariableDeclaration: + precedingNode = ctorDeclaration.parent.parent; + if ((ctorDeclaration.parent).declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, /*inList*/ true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration as VariableDeclaration); + break; + } + + if (!newClassDeclaration) { + return []; + } + + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (const deleteCallback of deletes) { + deleteCallback(); + } + + return [{ + description: formatStringFromArgs(Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + + function deleteNode(node: Node, inList = false) { + if (deletedNodes.some(n => isNodeDescendantOf(node, n))) { + // Parent node has already been deleted; do nothing + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(() => changeTracker.deleteNodeInList(sourceFile, node)); + } + else { + deletes.push(() => changeTracker.deleteNode(sourceFile, node)); + } + } + + function createClassElementsFromSymbol(symbol: Symbol) { + const memberElements: ClassElement[] = []; + // all instance members are stored in the "member" array of symbol + if (symbol.members) { + symbol.members.forEach(member => { + const memberElement = createClassElement(member, /*modifiers*/ undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + + // all static members are stored in the "exports" array of symbol + if (symbol.exports) { + symbol.exports.forEach(member => { + const memberElement = createClassElement(member, [createToken(SyntaxKind.StaticKeyword)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + + return memberElements; + + function shouldConvertDeclaration(_target: PropertyAccessExpression, source: Expression) { + // Right now the only thing we can convert are function expressions - other values shouldn't get + // transformed. We can update this once ES public class properties are available. + return isFunctionLike(source); + } + + function createClassElement(symbol: Symbol, modifiers: Modifier[]): ClassElement { + // both properties and methods are bound as property symbols + if (!(symbol.flags & SymbolFlags.Property)) { + return; + } + + const memberDeclaration = symbol.valueDeclaration as PropertyAccessExpression; + const assignmentBinaryExpression = memberDeclaration.parent as BinaryExpression; + + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + + // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end + const nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === SyntaxKind.ExpressionStatement + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + + if (!assignmentBinaryExpression.right) { + return createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + + switch (assignmentBinaryExpression.right.kind) { + case SyntaxKind.FunctionExpression: + const functionExpression = assignmentBinaryExpression.right as FunctionExpression; + return createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + + case SyntaxKind.ArrowFunction: + const arrowFunction = assignmentBinaryExpression.right as ArrowFunction; + const arrowFunctionBody = arrowFunction.body; + let bodyBlock: Block; + + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === SyntaxKind.Block) { + bodyBlock = arrowFunctionBody as Block; + } + // case 2: () => [1,2,3] + else { + const expression = arrowFunctionBody as Expression; + bodyBlock = createBlock([createReturn(expression)]); + } + return createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + + default: + // Don't try to declare members in JavaScript files + if (isSourceFileJavaScript(sourceFile)) { + return; + } + return createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + } + } + } + + function createClassFromVariableDeclaration(node: VariableDeclaration): ClassDeclaration { + const initializer = node.initializer as FunctionExpression; + if (!initializer || initializer.kind !== SyntaxKind.FunctionExpression) { + return undefined; + } + + if (node.name.kind !== SyntaxKind.Identifier) { + return undefined; + } + + const memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + + return createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + + function createClassFromFunctionDeclaration(node: FunctionDeclaration): ClassDeclaration { + const memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + return createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + } +} \ No newline at end of file diff --git a/src/services/refactors/refactors.ts b/src/services/refactors/refactors.ts new file mode 100644 index 00000000000..4c4ecb33416 --- /dev/null +++ b/src/services/refactors/refactors.ts @@ -0,0 +1 @@ +/// diff --git a/src/services/rename.ts b/src/services/rename.ts index 27c47179052..6091c0b2d03 100644 --- a/src/services/rename.ts +++ b/src/services/rename.ts @@ -53,7 +53,7 @@ namespace ts.Rename { } } - function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: string, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfo { + function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: ScriptElementKind, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfo { return { canRename: true, kind, diff --git a/src/services/services.ts b/src/services/services.ts index 6f0ee9e3f77..21c756a9acc 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -25,7 +25,9 @@ /// /// /// +/// /// +/// namespace ts { /** The version of the language service API */ @@ -105,6 +107,7 @@ namespace ts { scanner.setTextPos(pos); while (pos < end) { const token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan(); + Debug.assert(token !== SyntaxKind.EndOfFileToken); // Else it would infinitely loop const textPos = scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); @@ -133,10 +136,15 @@ namespace ts { } private createChildren(sourceFile?: SourceFileLike) { - let children: Node[]; - if (this.kind >= SyntaxKind.FirstNode) { + if (isJSDocTag(this)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + const children: Node[] = []; + this.forEachChild(child => { children.push(child); }); + this._children = children; + } + else if (this.kind >= SyntaxKind.FirstNode) { + const children: Node[] = []; scanner.setText((sourceFile || this.getSourceFile()).text); - children = []; let pos = this.pos; const useJSDocScanner = this.kind >= SyntaxKind.FirstJSDocTagNode && this.kind <= SyntaxKind.LastJSDocTagNode; const processNode = (node: Node) => { @@ -153,7 +161,7 @@ namespace ts { if (pos < nodes.pos) { pos = this.addSyntheticNodes(children, pos, nodes.pos, useJSDocScanner); } - children.push(this.createSyntaxList(>nodes)); + children.push(this.createSyntaxList(nodes)); pos = nodes.end; }; // jsDocComments need to be the first children @@ -171,8 +179,11 @@ namespace ts { this.addSyntheticNodes(children, pos, this.end); } scanner.setText(undefined); + this._children = children; + } + else { + this._children = emptyArray; } - this._children = children || emptyArray; } public getChildCount(sourceFile?: SourceFile): number { @@ -213,7 +224,7 @@ namespace ts { return child.kind < SyntaxKind.FirstNode ? child : child.getLastToken(sourceFile); } - public forEachChild(cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T { + public forEachChild(cbNode: (node: Node) => T, cbNodeArray?: (nodes: NodeArray) => T): T { return forEachChild(this, cbNode, cbNodeArray); } } @@ -298,15 +309,15 @@ namespace ts { class SymbolObject implements Symbol { flags: SymbolFlags; name: string; - declarations: Declaration[]; + declarations?: Declaration[]; // Undefined is used to indicate the value has not been computed. If, after computing, the - // symbol has no doc comment, then the empty string will be returned. - documentationComment: SymbolDisplayPart[]; + // symbol has no doc comment, then the empty array will be returned. + documentationComment?: SymbolDisplayPart[]; // Undefined is used to indicate the value has not been computed. If, after computing, the // symbol has no JSDoc tags, then the empty array will be returned. - tags: JSDocTagInfo[]; + tags?: JSDocTagInfo[]; constructor(flags: SymbolFlags, name: string) { this.flags = flags; @@ -321,7 +332,7 @@ namespace ts { return this.name; } - getDeclarations(): Declaration[] { + getDeclarations(): Declaration[] | undefined { return this.declarations; } @@ -360,6 +371,7 @@ namespace ts { _updateExpressionBrand: any; _unaryExpressionBrand: any; _expressionBrand: any; + /*@internal*/typeArguments: NodeArray; constructor(_kind: SyntaxKind.Identifier, pos: number, end: number) { super(pos, end); } @@ -371,7 +383,7 @@ namespace ts { flags: TypeFlags; objectFlags?: ObjectFlags; id: number; - symbol: Symbol; + symbol?: Symbol; constructor(checker: TypeChecker, flags: TypeFlags) { this.checker = checker; this.flags = flags; @@ -379,13 +391,13 @@ namespace ts { getFlags(): TypeFlags { return this.flags; } - getSymbol(): Symbol { + getSymbol(): Symbol | undefined { return this.symbol; } getProperties(): Symbol[] { return this.checker.getPropertiesOfType(this); } - getProperty(propertyName: string): Symbol { + getProperty(propertyName: string): Symbol | undefined { return this.checker.getPropertyOfType(this, propertyName); } getApparentProperties(): Symbol[] { @@ -397,13 +409,13 @@ namespace ts { getConstructSignatures(): Signature[] { return this.checker.getSignaturesOfType(this, SignatureKind.Construct); } - getStringIndexType(): Type { + getStringIndexType(): Type | undefined { return this.checker.getIndexTypeOfType(this, IndexKind.String); } - getNumberIndexType(): Type { + getNumberIndexType(): Type | undefined { return this.checker.getIndexTypeOfType(this, IndexKind.Number); } - getBaseTypes(): BaseType[] { + getBaseTypes(): BaseType[] | undefined { return this.flags & TypeFlags.Object && this.objectFlags & (ObjectFlags.Class | ObjectFlags.Interface) ? this.checker.getBaseTypes(this) : undefined; @@ -416,7 +428,7 @@ namespace ts { class SignatureObject implements Signature { checker: TypeChecker; declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; + typeParameters?: TypeParameter[]; parameters: Symbol[]; thisParameter: Symbol; resolvedReturnType: Type; @@ -426,12 +438,12 @@ namespace ts { hasLiteralTypes: boolean; // Undefined is used to indicate the value has not been computed. If, after computing, the - // symbol has no doc comment, then the empty string will be returned. - documentationComment: SymbolDisplayPart[]; + // symbol has no doc comment, then the empty array will be returned. + documentationComment?: SymbolDisplayPart[]; // Undefined is used to indicate the value has not been computed. If, after computing, the // symbol has no doc comment, then the empty array will be returned. - jsDocTags: JSDocTagInfo[]; + jsDocTags?: JSDocTagInfo[]; constructor(checker: TypeChecker) { this.checker = checker; @@ -439,7 +451,7 @@ namespace ts { getDeclaration(): SignatureDeclaration { return this.declaration; } - getTypeParameters(): TypeParameter[] { + getTypeParameters(): TypeParameter[] | undefined { return this.typeParameters; } getParameters(): Symbol[] { @@ -579,14 +591,15 @@ namespace ts { } function getDeclarationName(declaration: Declaration) { - if (declaration.name) { - const result = getTextOfIdentifierOrLiteral(declaration.name); + const name = getNameOfDeclaration(declaration); + if (name) { + const result = getTextOfIdentifierOrLiteral(name); if (result !== undefined) { return result; } - if (declaration.name.kind === SyntaxKind.ComputedPropertyName) { - const expr = (declaration.name).expression; + if (name.kind === SyntaxKind.ComputedPropertyName) { + const expr = (name).expression; if (expr.kind === SyntaxKind.PropertyAccessExpression) { return (expr).name.text; } @@ -1353,7 +1366,7 @@ namespace ts { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); - const node = getTouchingPropertyName(sourceFile, position); + const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -1416,7 +1429,7 @@ namespace ts { /// Goto implementation function getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] { synchronizeHostData(); - return FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// References and Occurrences @@ -1438,7 +1451,7 @@ namespace ts { synchronizeHostData(); const sourceFilesToSearch = map(filesToSearch, f => program.getSourceFile(f)); const sourceFile = getValidSourceFile(fileName); - return DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName: string, position: number): ReferenceEntry[] { @@ -1476,12 +1489,12 @@ namespace ts { function getReferences(fileName: string, position: number, options?: FindAllReferences.Options) { synchronizeHostData(); - return FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName: string, position: number): ReferencedSymbol[] { synchronizeHostData(); - return FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// NavigateTo @@ -1540,7 +1553,7 @@ namespace ts { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location - const node = getTouchingPropertyName(sourceFile, startPos); + const node = getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false); if (node === sourceFile) { return; @@ -1651,7 +1664,7 @@ namespace ts { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); const result: TextSpan[] = []; - const token = getTouchingToken(sourceFile, position); + const token = getTouchingToken(sourceFile, position, /*includeJsDocComment*/ false); if (token.getStart(sourceFile) === position) { const matchKind = getMatchingTokenKind(token); @@ -1853,8 +1866,7 @@ namespace ts { // OK, we have found a match in the file. This is only an acceptable match if // it is contained within a comment. - const token = getTokenAtPosition(sourceFile, matchPosition); - if (!isInsideComment(sourceFile, token, matchPosition)) { + if (!isInComment(sourceFile, matchPosition)) { continue; } @@ -1958,11 +1970,43 @@ namespace ts { return Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file: SourceFile, positionOrRange: number | TextRange, formatOptions?: FormatCodeSettings): RefactorContext { + const [startPosition, endPosition] = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end]; + return { + file, + startPosition, + endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken + }; + } + + function getApplicableRefactors(fileName: string, positionOrRange: number | TextRange): ApplicableRefactorInfo[] { + synchronizeHostData(); + const file = getValidSourceFile(fileName); + return refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + + function getRefactorCodeActions( + fileName: string, + formatOptions: FormatCodeSettings, + positionOrRange: number | TextRange, + refactorName: string): CodeAction[] | undefined { + + synchronizeHostData(); + const file = getValidSourceFile(fileName); + return refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } + return { dispose, cleanupSemanticCache, getSyntacticDiagnostics, getSemanticDiagnostics, + getApplicableRefactors, + getRefactorCodeActions, getCompilerOptionsDiagnostics, getSyntacticClassifications, getSemanticClassifications, diff --git a/src/services/shims.ts b/src/services/shims.ts index 29e24568460..498c1834a60 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -1038,7 +1038,11 @@ namespace ts { return this.forwardJSONCall(`resolveModuleName('${fileName}')`, () => { const compilerOptions = JSON.parse(compilerOptionsJson); const result = resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host); - const resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + let resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== Extension.Ts && result.resolvedModule.extension !== Extension.Tsx && result.resolvedModule.extension !== Extension.Dts) { + resolvedFileName = undefined; + } + return { resolvedFileName, failedLookupLocations: result.failedLookupLocations diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 1487bb410a5..b250ad49467 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -1,168 +1,6 @@ /// /* @internal */ namespace ts.SignatureHelp { - - // A partially written generic type expression is not guaranteed to have the correct syntax tree. the expression could be parsed as less than/greater than expression or a comma expression - // or some other combination depending on what the user has typed so far. For the purposes of signature help we need to consider any location after "<" as a possible generic type reference. - // To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it - // will return the generic identifier that started the expression (e.g. "foo" in "foonode.parent; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a signature help session diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 41bdf4d8ada..910c31c36b3 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -1,7 +1,7 @@ /* @internal */ namespace ts.SymbolDisplay { // TODO(drosen): use contextual SemanticMeaning. - export function getSymbolKind(typeChecker: TypeChecker, symbol: Symbol, location: Node): string { + export function getSymbolKind(typeChecker: TypeChecker, symbol: Symbol, location: Node): ScriptElementKind { const { flags } = symbol; if (flags & SymbolFlags.Class) return getDeclarationOfKind(symbol, SyntaxKind.ClassExpression) ? @@ -22,7 +22,7 @@ namespace ts.SymbolDisplay { return result; } - function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker: TypeChecker, symbol: Symbol, location: Node) { + function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker: TypeChecker, symbol: Symbol, location: Node): ScriptElementKind { if (typeChecker.isUndefinedSymbol(symbol)) { return ScriptElementKind.variableElement; } @@ -120,7 +120,7 @@ namespace ts.SymbolDisplay { // try get the call/construct signature from the type if it matches let callExpressionLike: CallExpression | NewExpression | JsxOpeningLikeElement; - if (location.kind === SyntaxKind.CallExpression || location.kind === SyntaxKind.NewExpression) { + if (isCallOrNewExpression(location)) { callExpressionLike = location; } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { @@ -200,27 +200,33 @@ namespace ts.SymbolDisplay { (location.kind === SyntaxKind.ConstructorKeyword && location.parent.kind === SyntaxKind.Constructor)) { // At constructor keyword of constructor declaration // get the signature from the declaration and write it const functionDeclaration = location.parent; - const allSignatures = functionDeclaration.kind === SyntaxKind.Constructor ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); - if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); - } - else { - signature = allSignatures[0]; - } + // Use function declaration to write the signatures only if the symbol corresponding to this declaration + const locationIsSymbolDeclaration = findDeclaration(symbol, declaration => + declaration === (location.kind === SyntaxKind.ConstructorKeyword ? functionDeclaration.parent : functionDeclaration)); - if (functionDeclaration.kind === SyntaxKind.Constructor) { - // show (constructor) Type(...) signature - symbolKind = ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === SyntaxKind.CallSignature && - !(type.symbol.flags & SymbolFlags.TypeLiteral || type.symbol.flags & SymbolFlags.ObjectLiteral) ? type.symbol : symbol, symbolKind); - } + if (locationIsSymbolDeclaration) { + const allSignatures = functionDeclaration.kind === SyntaxKind.Constructor ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); + } + else { + signature = allSignatures[0]; + } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; + if (functionDeclaration.kind === SyntaxKind.Constructor) { + // show (constructor) Type(...) signature + symbolKind = ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + // (function/method) symbol(..signature) + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === SyntaxKind.CallSignature && + !(type.symbol.flags & SymbolFlags.TypeLiteral || type.symbol.flags & SymbolFlags.ObjectLiteral) ? type.symbol : symbol, symbolKind); + } + + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; + } } } } @@ -269,7 +275,7 @@ namespace ts.SymbolDisplay { } if (symbolFlags & SymbolFlags.Module) { addNewLineIfDisplayPartsExist(); - const declaration = getDeclarationOfKind(symbol, SyntaxKind.ModuleDeclaration); + const declaration = getDeclarationOfKind(symbol, SyntaxKind.ModuleDeclaration); const isNamespace = declaration && declaration.name && declaration.name.kind === SyntaxKind.Identifier; displayParts.push(keywordPart(isNamespace ? SyntaxKind.NamespaceKeyword : SyntaxKind.ModuleKeyword)); displayParts.push(spacePart()); @@ -290,9 +296,9 @@ namespace ts.SymbolDisplay { } else { // Method/function type parameter - let declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeParameter); - Debug.assert(declaration !== undefined); - declaration = declaration.parent; + const decl = getDeclarationOfKind(symbol, SyntaxKind.TypeParameter); + Debug.assert(decl !== undefined); + const declaration = decl.parent; if (declaration) { if (isFunctionLikeKind(declaration.kind)) { @@ -330,7 +336,8 @@ namespace ts.SymbolDisplay { displayParts.push(spacePart()); displayParts.push(operatorPart(SyntaxKind.EqualsToken)); displayParts.push(spacePart()); - displayParts.push(displayPart(constantValue.toString(), SymbolDisplayPartKind.numericLiteral)); + displayParts.push(displayPart(getTextOfConstantValue(constantValue), + typeof constantValue === "number" ? SymbolDisplayPartKind.numericLiteral : SymbolDisplayPartKind.stringLiteral)); } } } diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 7ff0c37fa93..5aa4ebca7d0 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -157,7 +157,7 @@ namespace ts.textChanges { private changes: Change[] = []; private readonly newLineCharacter: string; - public static fromCodeFixContext(context: CodeFixContext) { + public static fromCodeFixContext(context: { newLineCharacter: string, rulesProvider: formatting.RulesProvider }) { return new ChangeTracker(context.newLineCharacter === "\n" ? NewLineKind.LineFeed : NewLineKind.CarriageReturnLineFeed, context.rulesProvider); } @@ -202,7 +202,7 @@ namespace ts.textChanges { return this; } if (index !== containingList.length - 1) { - const nextToken = getTokenAtPosition(sourceFile, node.end); + const nextToken = getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(node, nextToken)) { // find first non-whitespace position in the leading trivia of the node const startPosition = skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); @@ -214,7 +214,7 @@ namespace ts.textChanges { } } else { - const previousToken = getTokenAtPosition(sourceFile, containingList[index - 1].end); + const previousToken = getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); if (previousToken && isSeparator(node, previousToken)) { this.deleteNodeRange(sourceFile, previousToken, node); } @@ -254,9 +254,9 @@ namespace ts.textChanges { public insertNodeAfter(sourceFile: SourceFile, after: Node, newNode: Node, options: InsertNodeOptions & ConfigurableEnd = {}) { if ((isStatementButNotDeclaration(after)) || - after.kind === SyntaxKind.PropertyDeclaration || - after.kind === SyntaxKind.PropertySignature || - after.kind === SyntaxKind.MethodSignature) { + after.kind === SyntaxKind.PropertyDeclaration || + after.kind === SyntaxKind.PropertySignature || + after.kind === SyntaxKind.MethodSignature) { // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== CharacterCodes.semicolon) { @@ -292,7 +292,7 @@ namespace ts.textChanges { if (index !== containingList.length - 1) { // any element except the last one // use next sibling as an anchor - const nextToken = getTokenAtPosition(sourceFile, after.end); + const nextToken = getTokenAtPosition(sourceFile, after.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(after, nextToken)) { // for list // a, b, c @@ -481,7 +481,7 @@ namespace ts.textChanges { return (options.prefix || "") + text + (options.suffix || ""); } - private static normalize(changes: Change[]) { + private static normalize(changes: Change[]): Change[] { // order changes by start position const normalized = stableSort(changes, (a, b) => a.range.pos - b.range.pos); // verify that change intervals do not overlap, except possibly at end points. @@ -497,8 +497,8 @@ namespace ts.textChanges { readonly node: Node; } - export function getNonformattedText(node: Node, sourceFile: SourceFile, newLine: NewLineKind): NonFormattedText { - const options = { newLine, target: sourceFile.languageVersion }; + export function getNonformattedText(node: Node, sourceFile: SourceFile | undefined, newLine: NewLineKind): NonFormattedText { + const options = { newLine, target: sourceFile && sourceFile.languageVersion }; const writer = new Writer(getNewLineCharacter(options)); const printer = createPrinter(options, writer); printer.writeNode(EmitHint.Unspecified, node, sourceFile, writer); @@ -528,26 +528,6 @@ namespace ts.textChanges { return skipTrivia(s, 0) === s.length; } - const nullTransformationContext: TransformationContext = { - enableEmitNotification: noop, - enableSubstitution: noop, - endLexicalEnvironment: () => undefined, - getCompilerOptions: notImplemented, - getEmitHost: notImplemented, - getEmitResolver: notImplemented, - hoistFunctionDeclaration: noop, - hoistVariableDeclaration: noop, - isEmitNotificationEnabled: notImplemented, - isSubstitutionEnabled: notImplemented, - onEmitNode: noop, - onSubstituteNode: notImplemented, - readEmitHelpers: notImplemented, - requestEmitHelper: noop, - resumeLexicalEnvironment: noop, - startLexicalEnvironment: noop, - suspendLexicalEnvironment: noop - }; - function assignPositionsToNode(node: Node): Node { const visited = visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // create proxy node for non synthesized nodes @@ -580,6 +560,8 @@ namespace ts.textChanges { public readonly onEmitNode: PrintHandlers["onEmitNode"]; public readonly onBeforeEmitNodeArray: PrintHandlers["onBeforeEmitNodeArray"]; public readonly onAfterEmitNodeArray: PrintHandlers["onAfterEmitNodeArray"]; + public readonly onBeforeEmitToken: PrintHandlers["onBeforeEmitToken"]; + public readonly onAfterEmitToken: PrintHandlers["onAfterEmitToken"]; constructor(newLine: string) { this.writer = createTextWriter(newLine); @@ -602,6 +584,16 @@ namespace ts.textChanges { setEnd(nodes, this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = node => { + if (node) { + setPos(node, this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = node => { + if (node) { + setEnd(node, this.lastNonTriviaPosition); + } + }; } private setLastNonTriviaPosition(s: string, force: boolean) { diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 978195a31f6..0c1d76e7ae5 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -64,34 +64,12 @@ "signatureHelp.ts", "symbolDisplay.ts", "textChanges.ts", - "formatting/formatting.ts", - "formatting/formattingContext.ts", - "formatting/formattingRequestKind.ts", - "formatting/formattingScanner.ts", - "formatting/references.ts", - "formatting/rule.ts", - "formatting/ruleAction.ts", - "formatting/ruleDescriptor.ts", - "formatting/ruleFlag.ts", - "formatting/ruleOperation.ts", - "formatting/ruleOperationContext.ts", - "formatting/rules.ts", - "formatting/rulesMap.ts", - "formatting/rulesProvider.ts", - "formatting/smartIndenter.ts", - "formatting/tokenRange.ts", - "codeFixProvider.ts", - "codefixes/fixAddMissingMember.ts", - "codefixes/fixExtendsInterfaceBecomesImplements.ts", - "codefixes/fixClassIncorrectlyImplementsInterface.ts", - "codefixes/fixClassDoesntImplementInheritedAbstractMember.ts", - "codefixes/fixClassSuperMustPrecedeThisAccess.ts", - "codefixes/fixConstructorForDerivedNeedSuperCall.ts", - "codefixes/fixForgottenThisPropertyAccess.ts", - "codefixes/fixes.ts", - "codefixes/helpers.ts", - "codefixes/importFixes.ts", - "codefixes/unusedIdentifierFixes.ts", - "codefixes/disableJsDiagnostics.ts" + "refactorProvider.ts", + "codeFixProvider.ts" + ], + "include": [ + "formatting/*", + "codefixes/*", + "refactors/*" ] -} \ No newline at end of file +} diff --git a/src/services/types.ts b/src/services/types.ts index b1137bc4bc9..e042276e650 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -19,34 +19,34 @@ namespace ts { getFirstToken(sourceFile?: SourceFile): Node; getLastToken(sourceFile?: SourceFile): Node; // See ts.forEachChild for documentation. - forEachChild(cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; } export interface Symbol { getFlags(): SymbolFlags; getName(): string; - getDeclarations(): Declaration[]; + getDeclarations(): Declaration[] | undefined; getDocumentationComment(): SymbolDisplayPart[]; getJsDocTags(): JSDocTagInfo[]; } export interface Type { getFlags(): TypeFlags; - getSymbol(): Symbol; + getSymbol(): Symbol | undefined; getProperties(): Symbol[]; - getProperty(propertyName: string): Symbol; + getProperty(propertyName: string): Symbol | undefined; getApparentProperties(): Symbol[]; getCallSignatures(): Signature[]; getConstructSignatures(): Signature[]; - getStringIndexType(): Type; - getNumberIndexType(): Type; - getBaseTypes(): BaseType[]; + getStringIndexType(): Type | undefined; + getNumberIndexType(): Type | undefined; + getBaseTypes(): BaseType[] | undefined; getNonNullableType(): Type; } export interface Signature { getDeclaration(): SignatureDeclaration; - getTypeParameters(): TypeParameter[]; + getTypeParameters(): TypeParameter[] | undefined; getParameters(): Symbol[]; getReturnType(): Type; getDocumentationComment(): SymbolDisplayPart[]; @@ -261,6 +261,8 @@ namespace ts { isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; + getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; @@ -284,7 +286,7 @@ namespace ts { export interface ClassifiedSpan { textSpan: TextSpan; - classificationType: string; // ClassificationTypeNames + classificationType: ClassificationTypeNames; } /** @@ -295,7 +297,7 @@ namespace ts { */ export interface NavigationBarItem { text: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; spans: TextSpan[]; childItems: NavigationBarItem[]; @@ -311,8 +313,7 @@ namespace ts { export interface NavigationTree { /** Name of the declaration, or a short description, e.g. "". */ text: string; - /** A ScriptElementKind */ - kind: string; + kind: ScriptElementKind; /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ kindModifiers: string; /** @@ -352,6 +353,11 @@ namespace ts { changes: FileTextChanges[]; } + export interface ApplicableRefactorInfo { + name: string; + description: string; + } + export interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -373,7 +379,7 @@ namespace ts { } export interface ImplementationLocation extends DocumentSpan { - kind: string; + kind: ScriptElementKind; displayParts: SymbolDisplayPart[]; } @@ -382,30 +388,30 @@ namespace ts { highlightSpans: HighlightSpan[]; } - export namespace HighlightSpanKind { - export const none = "none"; - export const definition = "definition"; - export const reference = "reference"; - export const writtenReference = "writtenReference"; + export const enum HighlightSpanKind { + none = "none", + definition = "definition", + reference = "reference", + writtenReference = "writtenReference", } export interface HighlightSpan { fileName?: string; isInString?: true; textSpan: TextSpan; - kind: string; + kind: HighlightSpanKind; } export interface NavigateToItem { name: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; - matchKind: string; + matchKind: string; // TODO: keyof typeof PatternMatchKind; (https://github.com/Microsoft/TypeScript/issues/15102) isCaseSensitive: boolean; fileName: string; textSpan: TextSpan; containerName: string; - containerKind: string; + containerKind: ScriptElementKind; } export enum IndentStyle { @@ -473,9 +479,9 @@ namespace ts { export interface DefinitionInfo { fileName: string; textSpan: TextSpan; - kind: string; + kind: ScriptElementKind; name: string; - containerKind: string; + containerKind: ScriptElementKind; containerName: string; } @@ -515,7 +521,7 @@ namespace ts { export interface SymbolDisplayPart { text: string; - kind: string; // A ScriptElementKind + kind: string; } export interface JSDocTagInfo { @@ -524,7 +530,7 @@ namespace ts { } export interface QuickInfo { - kind: string; + kind: ScriptElementKind; kindModifiers: string; textSpan: TextSpan; displayParts: SymbolDisplayPart[]; @@ -537,7 +543,7 @@ namespace ts { localizedErrorMessage: string; displayName: string; fullDisplayName: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } @@ -590,7 +596,7 @@ namespace ts { export interface CompletionEntry { name: string; - kind: string; // see ScriptElementKind + kind: ScriptElementKind; kindModifiers: string; // see ScriptElementKindModifier, comma separated sortText: string; /** @@ -603,7 +609,7 @@ namespace ts { export interface CompletionEntryDetails { name: string; - kind: string; // see ScriptElementKind + kind: ScriptElementKind; kindModifiers: string; // see ScriptElementKindModifier, comma separated displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; @@ -701,141 +707,140 @@ namespace ts { getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; } - // TODO: move these to enums - export namespace ScriptElementKind { - export const unknown = ""; - export const warning = "warning"; + export const enum ScriptElementKind { + unknown = "", + warning = "warning", /** predefined type (void) or keyword (class) */ - export const keyword = "keyword"; + keyword = "keyword", /** top level script node */ - export const scriptElement = "script"; + scriptElement = "script", /** module foo {} */ - export const moduleElement = "module"; + moduleElement = "module", /** class X {} */ - export const classElement = "class"; + classElement = "class", /** var x = class X {} */ - export const localClassElement = "local class"; + localClassElement = "local class", /** interface Y {} */ - export const interfaceElement = "interface"; + interfaceElement = "interface", /** type T = ... */ - export const typeElement = "type"; + typeElement = "type", /** enum E */ - export const enumElement = "enum"; - export const enumMemberElement = "enum member"; + enumElement = "enum", + enumMemberElement = "enum member", /** * Inside module and script only * const v = .. */ - export const variableElement = "var"; + variableElement = "var", /** Inside function */ - export const localVariableElement = "local var"; + localVariableElement = "local var", /** * Inside module and script only * function f() { } */ - export const functionElement = "function"; + functionElement = "function", /** Inside function */ - export const localFunctionElement = "local function"; + localFunctionElement = "local function", /** class X { [public|private]* foo() {} } */ - export const memberFunctionElement = "method"; + memberFunctionElement = "method", /** class X { [public|private]* [get|set] foo:number; } */ - export const memberGetAccessorElement = "getter"; - export const memberSetAccessorElement = "setter"; + memberGetAccessorElement = "getter", + memberSetAccessorElement = "setter", /** * class X { [public|private]* foo:number; } * interface Y { foo:number; } */ - export const memberVariableElement = "property"; + memberVariableElement = "property", /** class X { constructor() { } } */ - export const constructorImplementationElement = "constructor"; + constructorImplementationElement = "constructor", /** interface Y { ():number; } */ - export const callSignatureElement = "call"; + callSignatureElement = "call", /** interface Y { []:number; } */ - export const indexSignatureElement = "index"; + indexSignatureElement = "index", /** interface Y { new():Y; } */ - export const constructSignatureElement = "construct"; + constructSignatureElement = "construct", /** function foo(*Y*: string) */ - export const parameterElement = "parameter"; + parameterElement = "parameter", - export const typeParameterElement = "type parameter"; + typeParameterElement = "type parameter", - export const primitiveType = "primitive type"; + primitiveType = "primitive type", - export const label = "label"; + label = "label", - export const alias = "alias"; + alias = "alias", - export const constElement = "const"; + constElement = "const", - export const letElement = "let"; + letElement = "let", - export const directory = "directory"; + directory = "directory", - export const externalModuleName = "external module name"; + externalModuleName = "external module name", /** * */ - export const jsxAttribute = "JSX attribute"; + jsxAttribute = "JSX attribute", } - export namespace ScriptElementKindModifier { - export const none = ""; - export const publicMemberModifier = "public"; - export const privateMemberModifier = "private"; - export const protectedMemberModifier = "protected"; - export const exportedModifier = "export"; - export const ambientModifier = "declare"; - export const staticModifier = "static"; - export const abstractModifier = "abstract"; + export const enum ScriptElementKindModifier { + none = "", + publicMemberModifier = "public", + privateMemberModifier = "private", + protectedMemberModifier = "protected", + exportedModifier = "export", + ambientModifier = "declare", + staticModifier = "static", + abstractModifier = "abstract", } - export class ClassificationTypeNames { - public static comment = "comment"; - public static identifier = "identifier"; - public static keyword = "keyword"; - public static numericLiteral = "number"; - public static operator = "operator"; - public static stringLiteral = "string"; - public static whiteSpace = "whitespace"; - public static text = "text"; + export const enum ClassificationTypeNames { + comment = "comment", + identifier = "identifier", + keyword = "keyword", + numericLiteral = "number", + operator = "operator", + stringLiteral = "string", + whiteSpace = "whitespace", + text = "text", - public static punctuation = "punctuation"; + punctuation = "punctuation", - public static className = "class name"; - public static enumName = "enum name"; - public static interfaceName = "interface name"; - public static moduleName = "module name"; - public static typeParameterName = "type parameter name"; - public static typeAliasName = "type alias name"; - public static parameterName = "parameter name"; - public static docCommentTagName = "doc comment tag name"; - public static jsxOpenTagName = "jsx open tag name"; - public static jsxCloseTagName = "jsx close tag name"; - public static jsxSelfClosingTagName = "jsx self closing tag name"; - public static jsxAttribute = "jsx attribute"; - public static jsxText = "jsx text"; - public static jsxAttributeStringLiteralValue = "jsx attribute string literal value"; + className = "class name", + enumName = "enum name", + interfaceName = "interface name", + moduleName = "module name", + typeParameterName = "type parameter name", + typeAliasName = "type alias name", + parameterName = "parameter name", + docCommentTagName = "doc comment tag name", + jsxOpenTagName = "jsx open tag name", + jsxCloseTagName = "jsx close tag name", + jsxSelfClosingTagName = "jsx self closing tag name", + jsxAttribute = "jsx attribute", + jsxText = "jsx text", + jsxAttributeStringLiteralValue = "jsx attribute string literal value", } export const enum ClassificationType { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index e884b342fef..2e771a73286 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -21,7 +21,6 @@ namespace ts { case SyntaxKind.PropertySignature: case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: - case SyntaxKind.EnumMember: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.Constructor: @@ -40,10 +39,13 @@ namespace ts { case SyntaxKind.TypeLiteral: return SemanticMeaning.Type; + case SyntaxKind.EnumMember: case SyntaxKind.ClassDeclaration: - case SyntaxKind.EnumDeclaration: return SemanticMeaning.Value | SemanticMeaning.Type; + case SyntaxKind.EnumDeclaration: + return SemanticMeaning.All; + case SyntaxKind.ModuleDeclaration: if (isAmbientModule(node)) { return SemanticMeaning.Namespace | SemanticMeaning.Value; @@ -61,7 +63,7 @@ namespace ts { case SyntaxKind.ImportDeclaration: case SyntaxKind.ExportAssignment: case SyntaxKind.ExportDeclaration: - return SemanticMeaning.Value | SemanticMeaning.Type | SemanticMeaning.Namespace; + return SemanticMeaning.All; // An external module can be a Value case SyntaxKind.SourceFile: @@ -238,7 +240,7 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.ModuleDeclaration: - return (node.parent).name === node; + return getNameOfDeclaration(node.parent) === node; case SyntaxKind.ElementAccessExpression: return (node.parent).argumentExpression === node; case SyntaxKind.ComputedPropertyName: @@ -254,37 +256,6 @@ namespace ts { getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } - /** Returns true if the position is within a comment */ - export function isInsideComment(sourceFile: SourceFile, token: Node, position: number): boolean { - // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - - function isInsideCommentRange(comments: CommentRange[]): boolean { - return forEach(comments, comment => { - // either we are 1. completely inside the comment, or 2. at the end of the comment - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - const text = sourceFile.text; - const width = comment.end - comment.pos; - // is single line comment or just /* - if (width <= 2 || text.charCodeAt(comment.pos + 1) === CharacterCodes.slash) { - return true; - } - else { - // is unterminated multi-line comment - return !(text.charCodeAt(comment.end - 1) === CharacterCodes.slash && - text.charCodeAt(comment.end - 2) === CharacterCodes.asterisk); - } - } - return false; - }); - } - } - export function getContainerNode(node: Node): Declaration { while (true) { node = node.parent; @@ -308,7 +279,7 @@ namespace ts { } } - export function getNodeKind(node: Node): string { + export function getNodeKind(node: Node): ScriptElementKind { switch (node.kind) { case SyntaxKind.SourceFile: return isExternalModule(node) ? ScriptElementKind.moduleElement : ScriptElementKind.scriptElement; @@ -355,7 +326,7 @@ namespace ts { return ScriptElementKind.unknown; } - function getKindOfVariableDeclaration(v: VariableDeclaration): string { + function getKindOfVariableDeclaration(v: VariableDeclaration): ScriptElementKind { return isConst(v) ? ScriptElementKind.constElement : isLet(v) @@ -619,29 +590,29 @@ namespace ts { /* Gets the token whose text has range [start, end) and * position >= start and (position < end or (position === end && token is keyword or identifier)) */ - export function getTouchingWord(sourceFile: SourceFile, position: number, includeJsDocComment = false): Node { - return getTouchingToken(sourceFile, position, n => isWord(n.kind), includeJsDocComment); + export function getTouchingWord(sourceFile: SourceFile, position: number, includeJsDocComment: boolean): Node { + return getTouchingToken(sourceFile, position, includeJsDocComment, n => isWord(n.kind)); } /* Gets the token whose text has range [start, end) and position >= start * and (position < end or (position === end && token is keyword or identifier or numeric/string literal)) */ - export function getTouchingPropertyName(sourceFile: SourceFile, position: number, includeJsDocComment = false): Node { - return getTouchingToken(sourceFile, position, n => isPropertyName(n.kind), includeJsDocComment); + export function getTouchingPropertyName(sourceFile: SourceFile, position: number, includeJsDocComment: boolean): Node { + return getTouchingToken(sourceFile, position, includeJsDocComment, n => isPropertyName(n.kind)); } /** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */ - export function getTouchingToken(sourceFile: SourceFile, position: number, includeItemAtEndPosition?: (n: Node) => boolean, includeJsDocComment = false): Node { + export function getTouchingToken(sourceFile: SourceFile, position: number, includeJsDocComment: boolean, includeItemAtEndPosition?: (n: Node) => boolean): Node { return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition, includeJsDocComment); } /** Returns a token if position is in [start-of-leading-trivia, end) */ - export function getTokenAtPosition(sourceFile: SourceFile, position: number, includeJsDocComment = false): Node { + export function getTokenAtPosition(sourceFile: SourceFile, position: number, includeJsDocComment: boolean): Node { return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined, includeJsDocComment); } /** Get the token whose text contains the position */ - function getTokenAtPositionWorker(sourceFile: SourceFile, position: number, allowPositionInLeadingTrivia: boolean, includeItemAtEndPosition: (n: Node) => boolean, includeJsDocComment = false): Node { + function getTokenAtPositionWorker(sourceFile: SourceFile, position: number, allowPositionInLeadingTrivia: boolean, includeItemAtEndPosition: (n: Node) => boolean, includeJsDocComment: boolean): Node { let current: Node = sourceFile; outer: while (true) { if (isToken(current)) { @@ -649,44 +620,26 @@ namespace ts { return current; } - if (includeJsDocComment) { - const jsDocChildren = ts.filter(current.getChildren(), isJSDocNode); - for (const jsDocChild of jsDocChildren) { - const start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - const end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === SyntaxKind.EndOfFileToken)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - const previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } - // find the child that contains 'position' for (const child of current.getChildren()) { - // all jsDocComment nodes were already visited - if (isJSDocNode(child)) { + if (isJSDocNode(child) && !includeJsDocComment) { continue; } + const start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - const end = child.getEnd(); - if (position < end || (position === end && child.kind === SyntaxKind.EndOfFileToken)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - const previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + continue; + } + + const end = child.getEnd(); + if (position < end || (position === end && child.kind === SyntaxKind.EndOfFileToken)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + const previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } @@ -706,7 +659,7 @@ namespace ts { export function findTokenOnLeftOfPosition(file: SourceFile, position: number): Node { // Ideally, getTokenAtPosition should return a token. However, it is currently // broken, so we do a check to make sure the result was indeed a token. - const tokenAtPosition = getTokenAtPosition(file, position); + const tokenAtPosition = getTokenAtPosition(file, position, /*includeJsDocComment*/ false); if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -832,15 +785,11 @@ namespace ts { return false; } - export function isInComment(sourceFile: SourceFile, position: number) { - return isInCommentHelper(sourceFile, position, /*predicate*/ undefined); - } - /** * returns true if the position is in between the open and close elements of an JSX expression. */ export function isInsideJsxElementOrAttribute(sourceFile: SourceFile, position: number) { - const token = getTokenAtPosition(sourceFile, position); + const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (!token) { return false; @@ -876,20 +825,35 @@ namespace ts { } export function isInTemplateString(sourceFile: SourceFile, position: number) { - const token = getTokenAtPosition(sourceFile, position); + const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); return isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } /** - * Returns true if the cursor at position in sourceFile is within a comment that additionally - * satisfies predicate, and false otherwise. + * Returns true if the cursor at position in sourceFile is within a comment. + * + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param predicate Additional predicate to test on the comment range. */ - export function isInCommentHelper(sourceFile: SourceFile, position: number, predicate?: (c: CommentRange) => boolean): boolean { - const token = getTokenAtPosition(sourceFile, position); + export function isInComment( + sourceFile: SourceFile, + position: number, + tokenAtPosition = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false), + predicate?: (c: CommentRange) => boolean): boolean { + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); - if (token && position <= token.getStart(sourceFile)) { - const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); + function isInCommentRange(commentRanges: CommentRange[]): boolean { + return forEach(commentRanges, c => isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c))); + } + } + function isPositionInCommentRange({ pos, end, kind }: ts.CommentRange, position: number, text: string): boolean { + if (pos < position && position < end) { + return true; + } + else if (position === end) { // The end marker of a single-line comment does not include the newline character. // In the following case, we are inside a comment (^ denotes the cursor position): // @@ -900,19 +864,17 @@ namespace ts { // /* asdf */^ // // Internally, we represent the end of the comment at the newline and closing '/', respectively. - return predicate ? - forEach(commentRanges, c => c.pos < position && - (c.kind === SyntaxKind.SingleLineCommentTrivia ? position <= c.end : position < c.end) && - predicate(c)) : - forEach(commentRanges, c => c.pos < position && - (c.kind === SyntaxKind.SingleLineCommentTrivia ? position <= c.end : position < c.end)); + return kind === SyntaxKind.SingleLineCommentTrivia || + // true for unterminated multi-line comment + !(text.charCodeAt(end - 1) === CharacterCodes.slash && text.charCodeAt(end - 2) === CharacterCodes.asterisk); + } + else { + return false; } - - return false; } export function hasDocComment(sourceFile: SourceFile, position: number) { - const token = getTokenAtPosition(sourceFile, position); + const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // First, we have to see if this position actually landed in a comment. const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); @@ -929,7 +891,7 @@ namespace ts { * Get the corresponding JSDocTag node if the position is in a jsDoc comment */ export function getJsDocTagAtPosition(sourceFile: SourceFile, position: number): JSDocTag { - let node = ts.getTokenAtPosition(sourceFile, position); + let node = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (isToken(node)) { switch (node.kind) { case SyntaxKind.VarKeyword: @@ -1091,27 +1053,27 @@ namespace ts { } export function isInReferenceComment(sourceFile: SourceFile, position: number): boolean { - return isInCommentHelper(sourceFile, position, isReferenceComment); - - function isReferenceComment(c: CommentRange): boolean { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, c => { const commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } export function isInNonReferenceComment(sourceFile: SourceFile, position: number): boolean { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - - function isNonReferenceComment(c: CommentRange): boolean { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, c => { const commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } export function createTextSpanFromNode(node: Node, sourceFile?: SourceFile): TextSpan { return createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } + export function createTextSpanFromRange(range: TextRange): TextSpan { + return createTextSpanFromBounds(range.pos, range.end); + } + export function isTypeKeyword(kind: SyntaxKind): boolean { switch (kind) { case SyntaxKind.AnyKeyword: @@ -1174,7 +1136,7 @@ namespace ts { clear: resetWriter, trackSymbol: noop, reportInaccessibleThisError: noop, - reportIllegalExtends: noop + reportPrivateInBaseOfClassExpression: noop, }; function writeIndent() { @@ -1396,6 +1358,6 @@ namespace ts { } export function getOpenBraceOfClassLike(declaration: ClassLikeDeclaration, sourceFile: SourceFile) { - return getTokenAtPosition(sourceFile, declaration.members.pos - 1); + return getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false); } } diff --git a/tests/baselines/reference/APISample_compile.js b/tests/baselines/reference/APISample_compile.js index c2617b2a6c6..35d49350457 100644 --- a/tests/baselines/reference/APISample_compile.js +++ b/tests/baselines/reference/APISample_compile.js @@ -1,6 +1,6 @@ //// [APISample_compile.ts] /* - * Note: This test is a public API sample. The sample sources can be found + * Note: This test is a public API sample. The sample sources can be found at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#a-minimal-compiler * Please log a "breaking change" issue for any API breaking change affecting this issue */ @@ -18,8 +18,12 @@ export function compile(fileNames: string[], options: ts.CompilerOptions): void var allDiagnostics = ts.getPreEmitDiagnostics(program); allDiagnostics.forEach(diagnostic => { - var { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); var message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + if (!diagnostic.file) { + console.log(message); + return; + } + var { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); }); @@ -31,7 +35,8 @@ export function compile(fileNames: string[], options: ts.CompilerOptions): void compile(process.argv.slice(2), { noEmitOnError: true, noImplicitAny: true, target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS -}); +}); + //// [APISample_compile.js] "use strict"; @@ -47,8 +52,12 @@ function compile(fileNames, options) { var emitResult = program.emit(); var allDiagnostics = ts.getPreEmitDiagnostics(program); allDiagnostics.forEach(function (diagnostic) { - var _a = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start), line = _a.line, character = _a.character; var message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + if (!diagnostic.file) { + console.log(message); + return; + } + var _a = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start), line = _a.line, character = _a.character; console.log(diagnostic.file.fileName + " (" + (line + 1) + "," + (character + 1) + "): " + message); }); var exitCode = emitResult.emitSkipped ? 1 : 0; diff --git a/tests/baselines/reference/APISample_watcher.js b/tests/baselines/reference/APISample_watcher.js index f06f9ced73f..b813a44f53e 100644 --- a/tests/baselines/reference/APISample_watcher.js +++ b/tests/baselines/reference/APISample_watcher.js @@ -1,6 +1,6 @@ //// [APISample_watcher.ts] /* - * Note: This test is a public API sample. The sample sources can be found + * Note: This test is a public API sample. The sample sources can be found at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#incremental-build-support-using-the-language-services * Please log a "breaking change" issue for any API breaking change affecting this issue */ @@ -91,7 +91,7 @@ function watch(rootFileNames: string[], options: ts.CompilerOptions) { allDiagnostics.forEach(diagnostic => { let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); if (diagnostic.file) { - let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); + let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); console.log(` Error ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); } else { @@ -106,7 +106,8 @@ const currentDirectoryFiles = fs.readdirSync(process.cwd()). filter(fileName=> fileName.length >= 3 && fileName.substr(fileName.length - 3, 3) === ".ts"); // Start the watcher -watch(currentDirectoryFiles, { module: ts.ModuleKind.CommonJS }); +watch(currentDirectoryFiles, { module: ts.ModuleKind.CommonJS }); + //// [APISample_watcher.js] "use strict"; diff --git a/tests/baselines/reference/ES5SymbolProperty5.errors.txt b/tests/baselines/reference/ES5SymbolProperty5.errors.txt index bbfb64b6459..fb3a9aa78d4 100644 --- a/tests/baselines/reference/ES5SymbolProperty5.errors.txt +++ b/tests/baselines/reference/ES5SymbolProperty5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/Symbols/ES5SymbolProperty5.ts(7,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/Symbols/ES5SymbolProperty5.ts(7,1): error TS2554: Expected 0 arguments, but got 1. ==== tests/cases/conformance/Symbols/ES5SymbolProperty5.ts (1 errors) ==== @@ -10,4 +10,4 @@ tests/cases/conformance/Symbols/ES5SymbolProperty5.ts(7,1): error TS2346: Suppli (new C)[Symbol.iterator](0) // Should error ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2554: Expected 0 arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json new file mode 100644 index 00000000000..064a040c58f --- /dev/null +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json @@ -0,0 +1,49 @@ +{ + "kind": "JSDocComment", + "pos": 0, + "end": 44, + "tags": { + "0": { + "kind": "JSDocParameterTag", + "pos": 8, + "end": 27, + "atToken": { + "kind": "AtToken", + "pos": 8, + "end": 9 + }, + "tagName": { + "kind": "Identifier", + "pos": 9, + "end": 12, + "text": "arg" + }, + "typeExpression": { + "kind": "JSDocTypeExpression", + "pos": 13, + "end": 21, + "type": { + "kind": "NumberKeyword", + "pos": 14, + "end": 20 + } + }, + "postParameterName": { + "kind": "Identifier", + "pos": 22, + "end": 27, + "text": "name1" + }, + "parameterName": { + "kind": "Identifier", + "pos": 22, + "end": 27, + "text": "name1" + }, + "comment": "Description" + }, + "length": 1, + "pos": 8, + "end": 27 + } +} \ No newline at end of file diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json new file mode 100644 index 00000000000..264b5850223 --- /dev/null +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json @@ -0,0 +1,49 @@ +{ + "kind": "JSDocComment", + "pos": 0, + "end": 49, + "tags": { + "0": { + "kind": "JSDocParameterTag", + "pos": 8, + "end": 32, + "atToken": { + "kind": "AtToken", + "pos": 8, + "end": 9 + }, + "tagName": { + "kind": "Identifier", + "pos": 9, + "end": 17, + "text": "argument" + }, + "typeExpression": { + "kind": "JSDocTypeExpression", + "pos": 18, + "end": 26, + "type": { + "kind": "NumberKeyword", + "pos": 19, + "end": 25 + } + }, + "postParameterName": { + "kind": "Identifier", + "pos": 27, + "end": 32, + "text": "name1" + }, + "parameterName": { + "kind": "Identifier", + "pos": 27, + "end": 32, + "text": "name1" + }, + "comment": "Description" + }, + "length": 1, + "pos": 8, + "end": 32 + } +} \ No newline at end of file diff --git a/tests/baselines/reference/ModuleWithExportedAndNonExportedFunctions.errors.txt b/tests/baselines/reference/ModuleWithExportedAndNonExportedFunctions.errors.txt index 96528577cbc..96864565d85 100644 --- a/tests/baselines/reference/ModuleWithExportedAndNonExportedFunctions.errors.txt +++ b/tests/baselines/reference/ModuleWithExportedAndNonExportedFunctions.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts(28,13): error TS2339: Property 'fn2' does not exist on type 'typeof A'. -tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts(29,14): error TS2339: Property 'fng2' does not exist on type 'typeof A'. +tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts(29,14): error TS2551: Property 'fng2' does not exist on type 'typeof A'. Did you mean 'fng'? ==== tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts (2 errors) ==== @@ -35,4 +35,4 @@ tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAnd !!! error TS2339: Property 'fn2' does not exist on type 'typeof A'. var fng2 = A.fng2; ~~~~ -!!! error TS2339: Property 'fng2' does not exist on type 'typeof A'. \ No newline at end of file +!!! error TS2551: Property 'fng2' does not exist on type 'typeof A'. Did you mean 'fng'? \ No newline at end of file diff --git a/tests/baselines/reference/anonymousClassExpression2.errors.txt b/tests/baselines/reference/anonymousClassExpression2.errors.txt index c9b59ae9c4d..6bc858bc542 100644 --- a/tests/baselines/reference/anonymousClassExpression2.errors.txt +++ b/tests/baselines/reference/anonymousClassExpression2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/anonymousClassExpression2.ts(13,18): error TS2339: Property 'methodA' does not exist on type 'B'. +tests/cases/compiler/anonymousClassExpression2.ts(13,18): error TS2551: Property 'methodA' does not exist on type 'B'. Did you mean 'methodB'? ==== tests/cases/compiler/anonymousClassExpression2.ts (1 errors) ==== @@ -16,7 +16,7 @@ tests/cases/compiler/anonymousClassExpression2.ts(13,18): error TS2339: Property methodB() { this.methodA; // error ~~~~~~~ -!!! error TS2339: Property 'methodA' does not exist on type 'B'. +!!! error TS2551: Property 'methodA' does not exist on type 'B'. Did you mean 'methodB'? this.methodB; // ok } } diff --git a/tests/baselines/reference/arrowFunctionExpressions.types b/tests/baselines/reference/arrowFunctionExpressions.types index aad43240daa..0de6c674d18 100644 --- a/tests/baselines/reference/arrowFunctionExpressions.types +++ b/tests/baselines/reference/arrowFunctionExpressions.types @@ -83,25 +83,25 @@ var p5 = ([a = 1]) => { }; >1 : 1 var p6 = ({ a }) => { }; ->p6 : ({a}: { a: any; }) => void ->({ a }) => { } : ({a}: { a: any; }) => void +>p6 : ({ a }: { a: any; }) => void +>({ a }) => { } : ({ a }: { a: any; }) => void >a : any var p7 = ({ a: { b } }) => { }; ->p7 : ({a: {b}}: { a: { b: any; }; }) => void ->({ a: { b } }) => { } : ({a: {b}}: { a: { b: any; }; }) => void +>p7 : ({ a: { b } }: { a: { b: any; }; }) => void +>({ a: { b } }) => { } : ({ a: { b } }: { a: { b: any; }; }) => void >a : any >b : any var p8 = ({ a = 1 }) => { }; ->p8 : ({a}: { a?: number; }) => void ->({ a = 1 }) => { } : ({a}: { a?: number; }) => void +>p8 : ({ a }: { a?: number; }) => void +>({ a = 1 }) => { } : ({ a }: { a?: number; }) => void >a : number >1 : 1 var p9 = ({ a: { b = 1 } = { b: 1 } }) => { }; ->p9 : ({a: {b}}: { a?: { b?: number; }; }) => void ->({ a: { b = 1 } = { b: 1 } }) => { } : ({a: {b}}: { a?: { b?: number; }; }) => void +>p9 : ({ a: { b } }: { a?: { b?: number; }; }) => void +>({ a: { b = 1 } = { b: 1 } }) => { } : ({ a: { b } }: { a?: { b?: number; }; }) => void >a : any >b : number >1 : 1 @@ -110,8 +110,8 @@ var p9 = ({ a: { b = 1 } = { b: 1 } }) => { }; >1 : 1 var p10 = ([{ value, done }]) => { }; ->p10 : ([{value, done}]: [{ value: any; done: any; }]) => void ->([{ value, done }]) => { } : ([{value, done}]: [{ value: any; done: any; }]) => void +>p10 : ([{ value, done }]: [{ value: any; done: any; }]) => void +>([{ value, done }]) => { } : ([{ value, done }]: [{ value: any; done: any; }]) => void >value : any >done : any diff --git a/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt b/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt index d3395c7ebc9..c8fb57e3616 100644 --- a/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt +++ b/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt @@ -1,8 +1,8 @@ tests/cases/compiler/assigningFromObjectToAnythingElse.ts(3,1): error TS2322: Type 'Object' is not assignable to type 'RegExp'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Property 'exec' is missing in type 'Object'. -tests/cases/compiler/assigningFromObjectToAnythingElse.ts(5,17): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/assigningFromObjectToAnythingElse.ts(6,17): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/assigningFromObjectToAnythingElse.ts(5,17): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/assigningFromObjectToAnythingElse.ts(6,17): error TS2558: Expected 0 type arguments, but got 1. tests/cases/compiler/assigningFromObjectToAnythingElse.ts(8,5): error TS2322: Type 'Object' is not assignable to type 'Error'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Property 'name' is missing in type 'Object'. @@ -19,10 +19,10 @@ tests/cases/compiler/assigningFromObjectToAnythingElse.ts(8,5): error TS2322: Ty var a: String = Object.create(""); ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var c: String = Object.create(1); ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var w: Error = new Object(); ~ diff --git a/tests/baselines/reference/assignmentRestElementWithErrorSourceType.errors.txt b/tests/baselines/reference/assignmentRestElementWithErrorSourceType.errors.txt index 080aca5a7ac..ff79716cab8 100644 --- a/tests/baselines/reference/assignmentRestElementWithErrorSourceType.errors.txt +++ b/tests/baselines/reference/assignmentRestElementWithErrorSourceType.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts(2,5): error TS2304: Cannot find name 'c'. -tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts(2,10): error TS2304: Cannot find name 'tupel'. +tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts(2,10): error TS2552: Cannot find name 'tupel'. Did you mean 'tuple'? ==== tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts (2 errors) ==== @@ -8,4 +8,4 @@ tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts(2,10): error TS ~ !!! error TS2304: Cannot find name 'c'. ~~~~~ -!!! error TS2304: Cannot find name 'tupel'. \ No newline at end of file +!!! error TS2552: Cannot find name 'tupel'. Did you mean 'tuple'? \ No newline at end of file diff --git a/tests/baselines/reference/autoLift2.errors.txt b/tests/baselines/reference/autoLift2.errors.txt index 9af3d59420f..63d1c2c3548 100644 --- a/tests/baselines/reference/autoLift2.errors.txt +++ b/tests/baselines/reference/autoLift2.errors.txt @@ -1,9 +1,9 @@ tests/cases/compiler/autoLift2.ts(5,14): error TS2339: Property 'foo' does not exist on type 'A'. tests/cases/compiler/autoLift2.ts(5,17): error TS1005: ';' expected. -tests/cases/compiler/autoLift2.ts(5,19): error TS2304: Cannot find name 'any'. +tests/cases/compiler/autoLift2.ts(5,19): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/autoLift2.ts(6,14): error TS2339: Property 'bar' does not exist on type 'A'. tests/cases/compiler/autoLift2.ts(6,17): error TS1005: ';' expected. -tests/cases/compiler/autoLift2.ts(6,19): error TS2304: Cannot find name 'any'. +tests/cases/compiler/autoLift2.ts(6,19): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/autoLift2.ts(12,11): error TS2339: Property 'foo' does not exist on type 'A'. tests/cases/compiler/autoLift2.ts(14,11): error TS2339: Property 'bar' does not exist on type 'A'. tests/cases/compiler/autoLift2.ts(16,33): error TS2339: Property 'foo' does not exist on type 'A'. @@ -21,14 +21,14 @@ tests/cases/compiler/autoLift2.ts(18,33): error TS2339: Property 'bar' does not ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. this.bar: any; ~~~ !!! error TS2339: Property 'bar' does not exist on type 'A'. ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. } diff --git a/tests/baselines/reference/badArrayIndex.errors.txt b/tests/baselines/reference/badArrayIndex.errors.txt index 4830ff1f693..decfebeeac7 100644 --- a/tests/baselines/reference/badArrayIndex.errors.txt +++ b/tests/baselines/reference/badArrayIndex.errors.txt @@ -1,10 +1,10 @@ -tests/cases/compiler/badArrayIndex.ts(1,15): error TS2304: Cannot find name 'number'. +tests/cases/compiler/badArrayIndex.ts(1,15): error TS2693: 'number' only refers to a type, but is being used as a value here. tests/cases/compiler/badArrayIndex.ts(1,22): error TS1109: Expression expected. ==== tests/cases/compiler/badArrayIndex.ts (2 errors) ==== var results = number[]; ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. ~ !!! error TS1109: Expression expected. \ No newline at end of file diff --git a/tests/baselines/reference/baseCheck.errors.txt b/tests/baselines/reference/baseCheck.errors.txt index 1f267f55301..0ae410d4e34 100644 --- a/tests/baselines/reference/baseCheck.errors.txt +++ b/tests/baselines/reference/baseCheck.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/baseCheck.ts(9,18): error TS2304: Cannot find name 'loc'. -tests/cases/compiler/baseCheck.ts(17,53): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/baseCheck.ts(9,18): error TS2552: Cannot find name 'loc'. Did you mean 'ELoc'? +tests/cases/compiler/baseCheck.ts(17,53): error TS2554: Expected 2 arguments, but got 1. tests/cases/compiler/baseCheck.ts(17,59): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. tests/cases/compiler/baseCheck.ts(18,62): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. tests/cases/compiler/baseCheck.ts(19,59): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. @@ -20,7 +20,7 @@ tests/cases/compiler/baseCheck.ts(26,9): error TS2304: Cannot find name 'x'. constructor(x: number) { super(0, loc); ~~~ -!!! error TS2304: Cannot find name 'loc'. +!!! error TS2552: Cannot find name 'loc'. Did you mean 'ELoc'? } m() { @@ -30,7 +30,7 @@ tests/cases/compiler/baseCheck.ts(26,9): error TS2304: Cannot find name 'x'. class D extends C { constructor(public z: number) { super(this.z) } } // too few params ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 1. ~~~~ !!! error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. class E extends C { constructor(public z: number) { super(0, this.z) } } diff --git a/tests/baselines/reference/bases.errors.txt b/tests/baselines/reference/bases.errors.txt index a61d35f664e..3069f977fe1 100644 --- a/tests/baselines/reference/bases.errors.txt +++ b/tests/baselines/reference/bases.errors.txt @@ -1,13 +1,13 @@ tests/cases/compiler/bases.ts(7,14): error TS2339: Property 'y' does not exist on type 'B'. tests/cases/compiler/bases.ts(7,15): error TS1005: ';' expected. -tests/cases/compiler/bases.ts(7,17): error TS2304: Cannot find name 'any'. +tests/cases/compiler/bases.ts(7,17): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/bases.ts(11,7): error TS2420: Class 'C' incorrectly implements interface 'I'. Property 'x' is missing in type 'C'. tests/cases/compiler/bases.ts(12,5): error TS2377: Constructors for derived classes must contain a 'super' call. tests/cases/compiler/bases.ts(13,9): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. tests/cases/compiler/bases.ts(13,14): error TS2339: Property 'x' does not exist on type 'C'. tests/cases/compiler/bases.ts(13,15): error TS1005: ';' expected. -tests/cases/compiler/bases.ts(13,17): error TS2304: Cannot find name 'any'. +tests/cases/compiler/bases.ts(13,17): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/bases.ts(17,9): error TS2339: Property 'x' does not exist on type 'C'. tests/cases/compiler/bases.ts(18,9): error TS2339: Property 'y' does not exist on type 'C'. @@ -25,7 +25,7 @@ tests/cases/compiler/bases.ts(18,9): error TS2339: Property 'y' does not exist o ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. } } @@ -44,7 +44,7 @@ tests/cases/compiler/bases.ts(18,9): error TS2339: Property 'y' does not exist o ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. } ~~~~~ !!! error TS2377: Constructors for derived classes must contain a 'super' call. diff --git a/tests/baselines/reference/bestCommonTypeOfTuple.types b/tests/baselines/reference/bestCommonTypeOfTuple.types index 82c96ecb86c..d62503b57d6 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple.types +++ b/tests/baselines/reference/bestCommonTypeOfTuple.types @@ -98,8 +98,8 @@ var e3 = t3[2]; // any >2 : 2 var e4 = t4[3]; // number ->e4 : number | E1 | E2 ->t4[3] : number | E1 | E2 +>e4 : number +>t4[3] : number >t4 : [E1, E2, number] >3 : 3 diff --git a/tests/baselines/reference/blockScopedNamespaceDifferentFile.js b/tests/baselines/reference/blockScopedNamespaceDifferentFile.js new file mode 100644 index 00000000000..3eab7477c09 --- /dev/null +++ b/tests/baselines/reference/blockScopedNamespaceDifferentFile.js @@ -0,0 +1,35 @@ +//// [tests/cases/compiler/blockScopedNamespaceDifferentFile.ts] //// + +//// [test.ts] +// #15734 failed when test.ts comes before typings.d.ts +namespace C { + export class Name { + static funcData = A.AA.func(); + static someConst = A.AA.foo; + + constructor(parameters) {} + } +} + +//// [typings.d.ts] +declare namespace A { + namespace AA { + function func(): number; + const foo = ""; + } +} + + +//// [out.js] +// #15734 failed when test.ts comes before typings.d.ts +var C; +(function (C) { + var Name = (function () { + function Name(parameters) { + } + return Name; + }()); + Name.funcData = A.AA.func(); + Name.someConst = A.AA.foo; + C.Name = Name; +})(C || (C = {})); diff --git a/tests/baselines/reference/blockScopedNamespaceDifferentFile.symbols b/tests/baselines/reference/blockScopedNamespaceDifferentFile.symbols new file mode 100644 index 00000000000..b7192d0e12b --- /dev/null +++ b/tests/baselines/reference/blockScopedNamespaceDifferentFile.symbols @@ -0,0 +1,44 @@ +=== tests/cases/compiler/test.ts === +// #15734 failed when test.ts comes before typings.d.ts +namespace C { +>C : Symbol(C, Decl(test.ts, 0, 0)) + + export class Name { +>Name : Symbol(Name, Decl(test.ts, 1, 13)) + + static funcData = A.AA.func(); +>funcData : Symbol(Name.funcData, Decl(test.ts, 2, 23)) +>A.AA.func : Symbol(A.AA.func, Decl(typings.d.ts, 1, 18)) +>A.AA : Symbol(A.AA, Decl(typings.d.ts, 0, 21)) +>A : Symbol(A, Decl(typings.d.ts, 0, 0)) +>AA : Symbol(A.AA, Decl(typings.d.ts, 0, 21)) +>func : Symbol(A.AA.func, Decl(typings.d.ts, 1, 18)) + + static someConst = A.AA.foo; +>someConst : Symbol(Name.someConst, Decl(test.ts, 3, 38)) +>A.AA.foo : Symbol(A.AA.foo, Decl(typings.d.ts, 3, 13)) +>A.AA : Symbol(A.AA, Decl(typings.d.ts, 0, 21)) +>A : Symbol(A, Decl(typings.d.ts, 0, 0)) +>AA : Symbol(A.AA, Decl(typings.d.ts, 0, 21)) +>foo : Symbol(A.AA.foo, Decl(typings.d.ts, 3, 13)) + + constructor(parameters) {} +>parameters : Symbol(parameters, Decl(test.ts, 6, 20)) + } +} + +=== tests/cases/compiler/typings.d.ts === +declare namespace A { +>A : Symbol(A, Decl(typings.d.ts, 0, 0)) + + namespace AA { +>AA : Symbol(AA, Decl(typings.d.ts, 0, 21)) + + function func(): number; +>func : Symbol(func, Decl(typings.d.ts, 1, 18)) + + const foo = ""; +>foo : Symbol(foo, Decl(typings.d.ts, 3, 13)) + } +} + diff --git a/tests/baselines/reference/blockScopedNamespaceDifferentFile.types b/tests/baselines/reference/blockScopedNamespaceDifferentFile.types new file mode 100644 index 00000000000..c03d51d2bc4 --- /dev/null +++ b/tests/baselines/reference/blockScopedNamespaceDifferentFile.types @@ -0,0 +1,46 @@ +=== tests/cases/compiler/test.ts === +// #15734 failed when test.ts comes before typings.d.ts +namespace C { +>C : typeof C + + export class Name { +>Name : Name + + static funcData = A.AA.func(); +>funcData : number +>A.AA.func() : number +>A.AA.func : () => number +>A.AA : typeof A.AA +>A : typeof A +>AA : typeof A.AA +>func : () => number + + static someConst = A.AA.foo; +>someConst : string +>A.AA.foo : "" +>A.AA : typeof A.AA +>A : typeof A +>AA : typeof A.AA +>foo : "" + + constructor(parameters) {} +>parameters : any + } +} + +=== tests/cases/compiler/typings.d.ts === +declare namespace A { +>A : typeof A + + namespace AA { +>AA : typeof AA + + function func(): number; +>func : () => number + + const foo = ""; +>foo : "" +>"" : "" + } +} + diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt index 3efa85d1cc7..77dc618f912 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt @@ -1,9 +1,9 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(3,18): error TS2393: Duplicate function implementation. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(5,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(5,9): error TS2554: Expected 0 arguments, but got 1. tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(8,18): error TS2393: Duplicate function implementation. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(10,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(12,5): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(10,9): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(12,5): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts (6 errors) ==== @@ -15,7 +15,7 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error T foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. } else { function foo() { } // duplicate function @@ -24,14 +24,14 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error T foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. } foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. foo(); } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt index 5d15278f098..c9a8c67296a 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt @@ -1,9 +1,9 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(3,18): error TS2393: Duplicate function implementation. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(5,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(5,9): error TS2554: Expected 0 arguments, but got 1. tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(8,18): error TS2393: Duplicate function implementation. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(10,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(12,5): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(10,9): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(12,5): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts (6 errors) ==== @@ -15,7 +15,7 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error T foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. } else { function foo() { } // duplicate @@ -24,14 +24,14 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error T foo(); foo(10);// not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. } foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. foo(); } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt index 36ce2d8c488..fb53f7a8f96 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt @@ -1,9 +1,9 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(4,18): error TS1250: Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(6,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(6,9): error TS2554: Expected 0 arguments, but got 1. tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(9,18): error TS1250: Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(11,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(14,5): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(11,9): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(14,5): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts (6 errors) ==== @@ -16,7 +16,7 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): e foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. } else { function foo() { } // Error to declare function in block scope @@ -25,14 +25,14 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): e foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt index 7b8834c5594..ae2bdcf587f 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(6,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(11,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(14,5): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(17,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(6,9): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(11,9): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(14,5): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(17,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts (4 errors) ==== @@ -12,21 +12,21 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(17,1): e foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. } else { function foo() { } foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. } foo(10); foo(); // not ok ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/callExpressionWithMissingTypeArgument1.errors.txt b/tests/baselines/reference/callExpressionWithMissingTypeArgument1.errors.txt index aef540d958a..9ac8c650e00 100644 --- a/tests/baselines/reference/callExpressionWithMissingTypeArgument1.errors.txt +++ b/tests/baselines/reference/callExpressionWithMissingTypeArgument1.errors.txt @@ -1,10 +1,16 @@ tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts(1,1): error TS2304: Cannot find name 'Foo'. +tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts(1,5): error TS2304: Cannot find name 'a'. tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts(1,7): error TS1110: Type expected. +tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts(1,8): error TS2304: Cannot find name 'b'. -==== tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts (2 errors) ==== +==== tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts (4 errors) ==== Foo(); ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'a'. ~ -!!! error TS1110: Type expected. \ No newline at end of file +!!! error TS1110: Type expected. + ~ +!!! error TS2304: Cannot find name 'b'. \ No newline at end of file diff --git a/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt b/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt index 0e8e8ff9303..6d95b588ebf 100644 --- a/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt +++ b/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt @@ -1,17 +1,17 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(5,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(6,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(9,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(10,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(13,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(14,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(21,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(22,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(28,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(29,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(36,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(37,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(43,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(44,11): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(5,10): error TS2558: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(6,11): error TS2558: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(9,10): error TS2558: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(10,11): error TS2558: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(13,10): error TS2558: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(14,11): error TS2558: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(21,10): error TS2558: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(22,11): error TS2558: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(28,10): error TS2558: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(29,11): error TS2558: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(36,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(37,11): error TS2558: Expected 0 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(43,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(44,11): error TS2558: Expected 0 type arguments, but got 3. ==== tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts (14 errors) ==== @@ -21,26 +21,26 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti function f(x: T, y: U): T { return null; } var r1 = f(1, ''); ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2 type arguments, but got 1. var r1b = f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2 type arguments, but got 3. var f2 = (x: T, y: U): T => { return null; } var r2 = f2(1, ''); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2 type arguments, but got 1. var r2b = f2(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2 type arguments, but got 3. var f3: { (x: T, y: U): T; } var r3 = f3(1, ''); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2 type arguments, but got 1. var r3b = f3(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2 type arguments, but got 3. class C { f(x: T, y: U): T { @@ -49,10 +49,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti } var r4 = (new C()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2 type arguments, but got 1. var r4b = (new C()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2 type arguments, but got 3. interface I { f(x: T, y: U): T; @@ -60,10 +60,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti var i: I; var r5 = i.f(1, ''); ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2 type arguments, but got 1. var r5b = i.f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2 type arguments, but got 3. class C2 { f(x: T, y: U): T { @@ -72,10 +72,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti } var r6 = (new C2()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var r6b = (new C2()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 3. interface I2 { f(x: T, y: U): T; @@ -83,7 +83,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti var i2: I2; var r7 = i2.f(1, ''); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var r7b = i2.f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2558: Expected 0 type arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt b/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt index 6a11751ead3..b014eae0fd8 100644 --- a/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt +++ b/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(5,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(8,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(11,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(18,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(24,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(31,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(37,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(5,9): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(8,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(11,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(18,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(24,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(31,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(37,10): error TS2558: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(40,10): error TS2347: Untyped function calls may not accept type arguments. tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(43,10): error TS2347: Untyped function calls may not accept type arguments. @@ -16,17 +16,17 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun function f(x: number) { return null; } var r = f(1); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var f2 = (x: number) => { return null; } var r2 = f2(1); ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var f3: { (x: number): any; } var r3 = f3(1); ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. class C { f(x: number) { @@ -35,7 +35,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun } var r4 = (new C()).f(1); ~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. interface I { f(x: number): any; @@ -43,7 +43,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun var i: I; var r5 = i.f(1); ~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. class C2 { f(x: number) { @@ -52,7 +52,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun } var r6 = (new C2()).f(1); ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. interface I2 { f(x: number); @@ -60,7 +60,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun var i2: I2; var r7 = i2.f(1); ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var a; var r8 = a(); diff --git a/tests/baselines/reference/callOnInstance.errors.txt b/tests/baselines/reference/callOnInstance.errors.txt index 4f80088ab75..5a6bb31ca28 100644 --- a/tests/baselines/reference/callOnInstance.errors.txt +++ b/tests/baselines/reference/callOnInstance.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/callOnInstance.ts(1,18): error TS2300: Duplicate identifier 'D'. tests/cases/compiler/callOnInstance.ts(3,15): error TS2300: Duplicate identifier 'D'. -tests/cases/compiler/callOnInstance.ts(7,19): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/compiler/callOnInstance.ts(7,19): error TS2350: Only a void function can be called with the 'new' keyword. +tests/cases/compiler/callOnInstance.ts(7,19): error TS2554: Expected 0 arguments, but got 1. tests/cases/compiler/callOnInstance.ts(10,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'C' has no compatible call signatures. @@ -18,9 +18,9 @@ tests/cases/compiler/callOnInstance.ts(10,1): error TS2349: Cannot invoke an exp var s2: string = (new D(1))(); ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. - ~~~~~~~~ !!! error TS2350: Only a void function can be called with the 'new' keyword. + ~~~~~~~~ +!!! error TS2554: Expected 0 arguments, but got 1. declare class C { constructor(value: number); } (new C(1))(); // Error for calling an instance diff --git a/tests/baselines/reference/callWithSpread2.errors.txt b/tests/baselines/reference/callWithSpread2.errors.txt new file mode 100644 index 00000000000..89617ab6074 --- /dev/null +++ b/tests/baselines/reference/callWithSpread2.errors.txt @@ -0,0 +1,81 @@ +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(30,5): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(31,5): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(32,13): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(33,13): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(34,11): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(35,11): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(36,1): error TS2556: Expected 1-3 arguments, but got a minimum of 0. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(37,1): error TS2556: Expected 1-3 arguments, but got a minimum of 0. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(38,1): error TS2556: Expected 1-3 arguments, but got a minimum of 0. + + +==== tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts (9 errors) ==== + declare function all(a?: number, b?: number): void; + declare function weird(a?: number | string, b?: number | string): void; + declare function prefix(s: string, a?: number, b?: number): void; + declare function rest(s: string, a?: number, b?: number, ...rest: number[]): void; + declare function normal(s: string): void; + declare function thunk(): string; + + declare var ns: number[]; + declare var mixed: (number | string)[]; + declare var tuple: [number, string]; + + // good + all(...ns) + weird(...ns) + weird(...mixed) + weird(...tuple) + prefix("a", ...ns) + rest("d", ...ns) + + + // this covers the arguments case + normal("g", ...ns) + normal("h", ...mixed) + normal("i", ...tuple) + thunk(...ns) + thunk(...mixed) + thunk(...tuple) + + // bad + all(...mixed) + ~~~~~~~~ +!!! error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. + all(...tuple) + ~~~~~~~~ +!!! error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. + prefix("b", ...mixed) + ~~~~~~~~ +!!! error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. + prefix("c", ...tuple) + ~~~~~~~~ +!!! error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. + rest("e", ...mixed) + ~~~~~~~~ +!!! error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. + rest("f", ...tuple) + ~~~~~~~~ +!!! error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. + prefix(...ns) // required parameters are required + ~~~~~~~~~~~~~ +!!! error TS2556: Expected 1-3 arguments, but got a minimum of 0. + prefix(...mixed) + ~~~~~~~~~~~~~~~~ +!!! error TS2556: Expected 1-3 arguments, but got a minimum of 0. + prefix(...tuple) + ~~~~~~~~~~~~~~~~ +!!! error TS2556: Expected 1-3 arguments, but got a minimum of 0. + \ No newline at end of file diff --git a/tests/baselines/reference/callWithSpread2.js b/tests/baselines/reference/callWithSpread2.js new file mode 100644 index 00000000000..55296d924f7 --- /dev/null +++ b/tests/baselines/reference/callWithSpread2.js @@ -0,0 +1,66 @@ +//// [callWithSpread2.ts] +declare function all(a?: number, b?: number): void; +declare function weird(a?: number | string, b?: number | string): void; +declare function prefix(s: string, a?: number, b?: number): void; +declare function rest(s: string, a?: number, b?: number, ...rest: number[]): void; +declare function normal(s: string): void; +declare function thunk(): string; + +declare var ns: number[]; +declare var mixed: (number | string)[]; +declare var tuple: [number, string]; + +// good +all(...ns) +weird(...ns) +weird(...mixed) +weird(...tuple) +prefix("a", ...ns) +rest("d", ...ns) + + +// this covers the arguments case +normal("g", ...ns) +normal("h", ...mixed) +normal("i", ...tuple) +thunk(...ns) +thunk(...mixed) +thunk(...tuple) + +// bad +all(...mixed) +all(...tuple) +prefix("b", ...mixed) +prefix("c", ...tuple) +rest("e", ...mixed) +rest("f", ...tuple) +prefix(...ns) // required parameters are required +prefix(...mixed) +prefix(...tuple) + + +//// [callWithSpread2.js] +// good +all.apply(void 0, ns); +weird.apply(void 0, ns); +weird.apply(void 0, mixed); +weird.apply(void 0, tuple); +prefix.apply(void 0, ["a"].concat(ns)); +rest.apply(void 0, ["d"].concat(ns)); +// this covers the arguments case +normal.apply(void 0, ["g"].concat(ns)); +normal.apply(void 0, ["h"].concat(mixed)); +normal.apply(void 0, ["i"].concat(tuple)); +thunk.apply(void 0, ns); +thunk.apply(void 0, mixed); +thunk.apply(void 0, tuple); +// bad +all.apply(void 0, mixed); +all.apply(void 0, tuple); +prefix.apply(void 0, ["b"].concat(mixed)); +prefix.apply(void 0, ["c"].concat(tuple)); +rest.apply(void 0, ["e"].concat(mixed)); +rest.apply(void 0, ["f"].concat(tuple)); +prefix.apply(void 0, ns); // required parameters are required +prefix.apply(void 0, mixed); +prefix.apply(void 0, tuple); diff --git a/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt b/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt index a3776946292..e3fca9dff9c 100644 --- a/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt +++ b/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(3,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(3,1): error TS2558: Expected 2 type arguments, but got 1. +tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(5,1): error TS2558: Expected 2 type arguments, but got 3. ==== tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts (2 errors) ==== @@ -7,8 +7,8 @@ tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(5,1): error TS2346: S f(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2 type arguments, but got 1. f(); f(); ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2558: Expected 2 type arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/cannotInvokeNewOnIndexExpression.errors.txt b/tests/baselines/reference/cannotInvokeNewOnIndexExpression.errors.txt index 7be5a1f086c..dbd10d775d9 100644 --- a/tests/baselines/reference/cannotInvokeNewOnIndexExpression.errors.txt +++ b/tests/baselines/reference/cannotInvokeNewOnIndexExpression.errors.txt @@ -1,7 +1,7 @@ -tests/cases/compiler/cannotInvokeNewOnIndexExpression.ts(1,23): error TS2304: Cannot find name 'any'. +tests/cases/compiler/cannotInvokeNewOnIndexExpression.ts(1,23): error TS2693: 'any' only refers to a type, but is being used as a value here. ==== tests/cases/compiler/cannotInvokeNewOnIndexExpression.ts (1 errors) ==== var test: any[] = new any[1]; ~~~ -!!! error TS2304: Cannot find name 'any'. \ No newline at end of file +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. \ No newline at end of file diff --git a/tests/baselines/reference/capturedVarInLoop.js b/tests/baselines/reference/capturedVarInLoop.js new file mode 100644 index 00000000000..303c18eda2d --- /dev/null +++ b/tests/baselines/reference/capturedVarInLoop.js @@ -0,0 +1,17 @@ +//// [capturedVarInLoop.ts] +for (var i = 0; i < 10; i++) { + var str = 'x', len = str.length; + let lambda1 = (y) => { }; + let lambda2 = () => lambda1(len); +} + +//// [capturedVarInLoop.js] +var _loop_1 = function () { + str = 'x', len = str.length; + var lambda1 = function (y) { }; + var lambda2 = function () { return lambda1(len); }; +}; +var str, len; +for (var i = 0; i < 10; i++) { + _loop_1(); +} diff --git a/tests/baselines/reference/capturedVarInLoop.symbols b/tests/baselines/reference/capturedVarInLoop.symbols new file mode 100644 index 00000000000..9f218154fd8 --- /dev/null +++ b/tests/baselines/reference/capturedVarInLoop.symbols @@ -0,0 +1,22 @@ +=== tests/cases/compiler/capturedVarInLoop.ts === +for (var i = 0; i < 10; i++) { +>i : Symbol(i, Decl(capturedVarInLoop.ts, 0, 8)) +>i : Symbol(i, Decl(capturedVarInLoop.ts, 0, 8)) +>i : Symbol(i, Decl(capturedVarInLoop.ts, 0, 8)) + + var str = 'x', len = str.length; +>str : Symbol(str, Decl(capturedVarInLoop.ts, 1, 7)) +>len : Symbol(len, Decl(capturedVarInLoop.ts, 1, 18)) +>str.length : Symbol(String.length, Decl(lib.d.ts, --, --)) +>str : Symbol(str, Decl(capturedVarInLoop.ts, 1, 7)) +>length : Symbol(String.length, Decl(lib.d.ts, --, --)) + + let lambda1 = (y) => { }; +>lambda1 : Symbol(lambda1, Decl(capturedVarInLoop.ts, 2, 7)) +>y : Symbol(y, Decl(capturedVarInLoop.ts, 2, 19)) + + let lambda2 = () => lambda1(len); +>lambda2 : Symbol(lambda2, Decl(capturedVarInLoop.ts, 3, 7)) +>lambda1 : Symbol(lambda1, Decl(capturedVarInLoop.ts, 2, 7)) +>len : Symbol(len, Decl(capturedVarInLoop.ts, 1, 18)) +} diff --git a/tests/baselines/reference/capturedVarInLoop.types b/tests/baselines/reference/capturedVarInLoop.types new file mode 100644 index 00000000000..37d78df8ba3 --- /dev/null +++ b/tests/baselines/reference/capturedVarInLoop.types @@ -0,0 +1,30 @@ +=== tests/cases/compiler/capturedVarInLoop.ts === +for (var i = 0; i < 10; i++) { +>i : number +>0 : 0 +>i < 10 : boolean +>i : number +>10 : 10 +>i++ : number +>i : number + + var str = 'x', len = str.length; +>str : string +>'x' : "x" +>len : number +>str.length : number +>str : string +>length : number + + let lambda1 = (y) => { }; +>lambda1 : (y: any) => void +>(y) => { } : (y: any) => void +>y : any + + let lambda2 = () => lambda1(len); +>lambda2 : () => void +>() => lambda1(len) : () => void +>lambda1(len) : void +>lambda1 : (y: any) => void +>len : number +} diff --git a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt new file mode 100644 index 00000000000..b409185a114 --- /dev/null +++ b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt @@ -0,0 +1,29 @@ +tests/cases/compiler/weird.js(1,1): error TS2304: Cannot find name 'someFunction'. +tests/cases/compiler/weird.js(1,23): error TS7006: Parameter 'BaseClass' implicitly has an 'any' type. +tests/cases/compiler/weird.js(6,13): error TS2346: Call target does not contain any signatures. +tests/cases/compiler/weird.js(9,17): error TS7006: Parameter 'error' implicitly has an 'any' type. + + +==== tests/cases/compiler/weird.js (4 errors) ==== + someFunction(function(BaseClass) { + ~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'someFunction'. + ~~~~~~~~~ +!!! error TS7006: Parameter 'BaseClass' implicitly has an 'any' type. + 'use strict'; + const DEFAULT_MESSAGE = "nop!"; + class Hello extends BaseClass { + constructor() { + super(); + ~~~~~~~ +!!! error TS2346: Call target does not contain any signatures. + this.foo = "bar"; + } + _render(error) { + ~~~~~ +!!! error TS7006: Parameter 'error' implicitly has an 'any' type. + const message = error.message || DEFAULT_MESSAGE; + } + } + }); + \ No newline at end of file diff --git a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.symbols b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.symbols new file mode 100644 index 00000000000..c9ee830a9a5 --- /dev/null +++ b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.symbols @@ -0,0 +1,17 @@ +=== tests/cases/compiler/weird.js === +someFunction(function(BaseClass) { +>BaseClass : Symbol(BaseClass, Decl(weird.js, 0, 22)) + + class Hello extends BaseClass { +>Hello : Symbol(Hello, Decl(weird.js, 0, 34)) +>BaseClass : Symbol(BaseClass, Decl(weird.js, 0, 22)) + + constructor() { + this.foo = "bar"; +>this.foo : Symbol(Hello.foo, Decl(weird.js, 2, 17)) +>this : Symbol(Hello, Decl(weird.js, 0, 34)) +>foo : Symbol(Hello.foo, Decl(weird.js, 2, 17)) + } + } +}); + diff --git a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.types b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.types new file mode 100644 index 00000000000..6a0a5ad1479 --- /dev/null +++ b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/weird.js === +someFunction(function(BaseClass) { +>someFunction(function(BaseClass) { class Hello extends BaseClass { constructor() { this.foo = "bar"; } }}) : any +>someFunction : any +>function(BaseClass) { class Hello extends BaseClass { constructor() { this.foo = "bar"; } }} : (BaseClass: any) => void +>BaseClass : any + + class Hello extends BaseClass { +>Hello : Hello +>BaseClass : any + + constructor() { + this.foo = "bar"; +>this.foo = "bar" : "bar" +>this.foo : string +>this : this +>foo : string +>"bar" : "bar" + } + } +}); + diff --git a/tests/baselines/reference/checkJsFiles7.symbols b/tests/baselines/reference/checkJsFiles7.symbols new file mode 100644 index 00000000000..a8214483b86 --- /dev/null +++ b/tests/baselines/reference/checkJsFiles7.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/a.js === +class C { +>C : Symbol(C, Decl(a.js, 0, 0)) + + constructor() { + /** @type {boolean} */ + this.a = true; +>this.a : Symbol(C.a, Decl(a.js, 1, 16), Decl(a.js, 3, 16)) +>this : Symbol(C, Decl(a.js, 0, 0)) +>a : Symbol(C.a, Decl(a.js, 1, 16), Decl(a.js, 3, 16)) + + this.a = !!this.a; +>this.a : Symbol(C.a, Decl(a.js, 1, 16), Decl(a.js, 3, 16)) +>this : Symbol(C, Decl(a.js, 0, 0)) +>a : Symbol(C.a, Decl(a.js, 1, 16), Decl(a.js, 3, 16)) +>this.a : Symbol(C.a, Decl(a.js, 1, 16), Decl(a.js, 3, 16)) +>this : Symbol(C, Decl(a.js, 0, 0)) +>a : Symbol(C.a, Decl(a.js, 1, 16), Decl(a.js, 3, 16)) + } +} diff --git a/tests/baselines/reference/checkJsFiles7.types b/tests/baselines/reference/checkJsFiles7.types new file mode 100644 index 00000000000..a86767b5e44 --- /dev/null +++ b/tests/baselines/reference/checkJsFiles7.types @@ -0,0 +1,25 @@ +=== tests/cases/compiler/a.js === +class C { +>C : C + + constructor() { + /** @type {boolean} */ + this.a = true; +>this.a = true : true +>this.a : boolean +>this : this +>a : boolean +>true : true + + this.a = !!this.a; +>this.a = !!this.a : boolean +>this.a : boolean +>this : this +>a : boolean +>!!this.a : boolean +>!this.a : boolean +>this.a : true +>this : this +>a : true + } +} diff --git a/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt b/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt index 758b295a49d..d9104608284 100644 --- a/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt +++ b/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/a.js(14,5): error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property. +tests/cases/compiler/a.js(14,10): error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property. ==== tests/cases/compiler/a.js (1 errors) ==== @@ -16,7 +16,7 @@ tests/cases/compiler/a.js(14,5): error TS2424: Class 'A' defines instance member constructor() { super(); this.foo = () => 3; - ~~~~~~~~~~~~~~~~~~ + ~~~ !!! error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property. } } diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.js b/tests/baselines/reference/checkJsxChildrenProperty12.js new file mode 100644 index 00000000000..0030d87483f --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty12.js @@ -0,0 +1,76 @@ +//// [file.tsx] +import React = require('react'); + +interface ButtonProp { + a: number, + b: string, + children: Button; +} + +class Button extends React.Component { + render() { + let condition: boolean; + if (condition) { + return + } + else { + return ( +
Hello World
+
); + } + } +} + +interface InnerButtonProp { + a: number +} + +class InnerButton extends React.Component { + render() { + return (); + } +} + + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var Button = (function (_super) { + __extends(Button, _super); + function Button() { + return _super !== null && _super.apply(this, arguments) || this; + } + Button.prototype.render = function () { + var condition; + if (condition) { + return ; + } + else { + return ( +
Hello World
+
); + } + }; + return Button; +}(React.Component)); +var InnerButton = (function (_super) { + __extends(InnerButton, _super); + function InnerButton() { + return _super !== null && _super.apply(this, arguments) || this; + } + InnerButton.prototype.render = function () { + return (); + }; + return InnerButton; +}(React.Component)); diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.symbols b/tests/baselines/reference/checkJsxChildrenProperty12.symbols new file mode 100644 index 00000000000..ccfb4b18875 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty12.symbols @@ -0,0 +1,80 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +interface ButtonProp { +>ButtonProp : Symbol(ButtonProp, Decl(file.tsx, 0, 32)) + + a: number, +>a : Symbol(ButtonProp.a, Decl(file.tsx, 2, 22)) + + b: string, +>b : Symbol(ButtonProp.b, Decl(file.tsx, 3, 14)) + + children: Button; +>children : Symbol(ButtonProp.children, Decl(file.tsx, 4, 14)) +>Button : Symbol(Button, Decl(file.tsx, 6, 1)) +} + +class Button extends React.Component { +>Button : Symbol(Button, Decl(file.tsx, 6, 1)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>ButtonProp : Symbol(ButtonProp, Decl(file.tsx, 0, 32)) + + render() { +>render : Symbol(Button.render, Decl(file.tsx, 8, 55)) + + let condition: boolean; +>condition : Symbol(condition, Decl(file.tsx, 10, 5)) + + if (condition) { +>condition : Symbol(condition, Decl(file.tsx, 10, 5)) + + return +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1)) +>this.props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) +>this : Symbol(Button, Decl(file.tsx, 6, 1)) +>props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) + } + else { + return ( +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1)) +>this.props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) +>this : Symbol(Button, Decl(file.tsx, 6, 1)) +>props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) + +
Hello World
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + +
); +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1)) + } + } +} + +interface InnerButtonProp { +>InnerButtonProp : Symbol(InnerButtonProp, Decl(file.tsx, 20, 1)) + + a: number +>a : Symbol(InnerButtonProp.a, Decl(file.tsx, 22, 27)) +} + +class InnerButton extends React.Component { +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>InnerButtonProp : Symbol(InnerButtonProp, Decl(file.tsx, 20, 1)) + + render() { +>render : Symbol(InnerButton.render, Decl(file.tsx, 26, 65)) + + return (); +>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43)) +>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43)) + } +} + diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.types b/tests/baselines/reference/checkJsxChildrenProperty12.types new file mode 100644 index 00000000000..93a7d0f9be1 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty12.types @@ -0,0 +1,86 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +interface ButtonProp { +>ButtonProp : ButtonProp + + a: number, +>a : number + + b: string, +>b : string + + children: Button; +>children : Button +>Button : Button +} + +class Button extends React.Component { +>Button : Button +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>ButtonProp : ButtonProp + + render() { +>render : () => JSX.Element + + let condition: boolean; +>condition : boolean + + if (condition) { +>condition : boolean + + return +> : JSX.Element +>InnerButton : typeof InnerButton +>this.props : ButtonProp & { children?: React.ReactNode; } +>this : this +>props : ButtonProp & { children?: React.ReactNode; } + } + else { + return ( +>(
Hello World
) : JSX.Element +>
Hello World
: JSX.Element +>InnerButton : typeof InnerButton +>this.props : ButtonProp & { children?: React.ReactNode; } +>this : this +>props : ButtonProp & { children?: React.ReactNode; } + +
Hello World
+>
Hello World
: JSX.Element +>div : any +>div : any + +
); +>InnerButton : typeof InnerButton + } + } +} + +interface InnerButtonProp { +>InnerButtonProp : InnerButtonProp + + a: number +>a : number +} + +class InnerButton extends React.Component { +>InnerButton : InnerButton +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>InnerButtonProp : InnerButtonProp + + render() { +>render : () => JSX.Element + + return (); +>() : JSX.Element +> : JSX.Element +>button : any +>button : any + } +} + diff --git a/tests/baselines/reference/checkJsxChildrenProperty13.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty13.errors.txt new file mode 100644 index 00000000000..c926980cab1 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty13.errors.txt @@ -0,0 +1,33 @@ +tests/cases/conformance/jsx/file.tsx(12,30): error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + import React = require('react'); + + interface ButtonProp { + a: number, + b: string, + children: Button; + } + + class Button extends React.Component { + render() { + // Error children are specified twice + return ( + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. +
Hello World
+
); + } + } + + interface InnerButtonProp { + a: number + } + + class InnerButton extends React.Component { + render() { + return (); + } + } + \ No newline at end of file diff --git a/tests/baselines/reference/checkJsxChildrenProperty13.js b/tests/baselines/reference/checkJsxChildrenProperty13.js new file mode 100644 index 00000000000..8947e6b211f --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty13.js @@ -0,0 +1,66 @@ +//// [file.tsx] +import React = require('react'); + +interface ButtonProp { + a: number, + b: string, + children: Button; +} + +class Button extends React.Component { + render() { + // Error children are specified twice + return ( +
Hello World
+
); + } +} + +interface InnerButtonProp { + a: number +} + +class InnerButton extends React.Component { + render() { + return (); + } +} + + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var Button = (function (_super) { + __extends(Button, _super); + function Button() { + return _super !== null && _super.apply(this, arguments) || this; + } + Button.prototype.render = function () { + // Error children are specified twice + return ( +
Hello World
+
); + }; + return Button; +}(React.Component)); +var InnerButton = (function (_super) { + __extends(InnerButton, _super); + function InnerButton() { + return _super !== null && _super.apply(this, arguments) || this; + } + InnerButton.prototype.render = function () { + return (); + }; + return InnerButton; +}(React.Component)); diff --git a/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt index 6bb91bd6385..aeeceb8652e 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt +++ b/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt @@ -2,7 +2,6 @@ tests/cases/conformance/jsx/file.tsx(14,15): error TS2322: Type '{ a: 10; b: "hi Type '{ a: 10; b: "hi"; }' is not assignable to type 'Prop'. Property 'children' is missing in type '{ a: 10; b: "hi"; }'. tests/cases/conformance/jsx/file.tsx(17,11): error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. -tests/cases/conformance/jsx/file.tsx(25,11): error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. tests/cases/conformance/jsx/file.tsx(31,11): error TS2322: Type '{ a: 10; b: "hi"; children: (Element | ((name: string) => Element))[]; }' is not assignable to type 'IntrinsicAttributes & Prop'. Type '{ a: 10; b: "hi"; children: (Element | ((name: string) => Element))[]; }' is not assignable to type 'Prop'. Types of property 'children' are incompatible. @@ -29,7 +28,7 @@ tests/cases/conformance/jsx/file.tsx(49,11): error TS2322: Type '{ a: 10; b: "hi Property 'type' is missing in type 'Element[]'. -==== tests/cases/conformance/jsx/file.tsx (7 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (6 errors) ==== import React = require('react'); interface Prop { @@ -61,8 +60,6 @@ tests/cases/conformance/jsx/file.tsx(49,11): error TS2322: Type '{ a: 10; b: "hi } let k1 = - ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. hi hi hi! ; diff --git a/tests/baselines/reference/checkJsxChildrenProperty4.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty4.errors.txt index d12c557102c..399b159f482 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty4.errors.txt +++ b/tests/baselines/reference/checkJsxChildrenProperty4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/jsx/file.tsx(24,28): error TS2339: Property 'NAme' does not exist on type 'IUser'. +tests/cases/conformance/jsx/file.tsx(24,28): error TS2551: Property 'NAme' does not exist on type 'IUser'. Did you mean 'Name'? tests/cases/conformance/jsx/file.tsx(32,9): error TS2322: Type '{ children: ((user: IUser) => Element)[]; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & IFetchUserProps & { children?: ReactNode; }'. Type '{ children: ((user: IUser) => Element)[]; }' is not assignable to type 'IFetchUserProps'. Types of property 'children' are incompatible. @@ -32,7 +32,7 @@ tests/cases/conformance/jsx/file.tsx(32,9): error TS2322: Type '{ children: ((us { user => (

{ user.NAme }

~~~~ -!!! error TS2339: Property 'NAme' does not exist on type 'IUser'. +!!! error TS2551: Property 'NAme' does not exist on type 'IUser'. Did you mean 'Name'? ) }
); diff --git a/tests/baselines/reference/classConstructorAccessibility.js b/tests/baselines/reference/classConstructorAccessibility.js index 46a548d0b54..4d120a3980f 100644 --- a/tests/baselines/reference/classConstructorAccessibility.js +++ b/tests/baselines/reference/classConstructorAccessibility.js @@ -89,7 +89,7 @@ declare class C { } declare class D { x: number; - private constructor(x); + private constructor(); } declare class E { x: number; diff --git a/tests/baselines/reference/classConstructorAccessibility2.js b/tests/baselines/reference/classConstructorAccessibility2.js index 7297af11a4e..76c8ea19110 100644 --- a/tests/baselines/reference/classConstructorAccessibility2.js +++ b/tests/baselines/reference/classConstructorAccessibility2.js @@ -135,7 +135,7 @@ declare class BaseB { } declare class BaseC { x: number; - private constructor(x); + private constructor(); createInstance(): void; static staticInstance(): void; } diff --git a/tests/baselines/reference/classConstructorAccessibility3.js b/tests/baselines/reference/classConstructorAccessibility3.js index 3e024970bcf..d1bd8f38c40 100644 --- a/tests/baselines/reference/classConstructorAccessibility3.js +++ b/tests/baselines/reference/classConstructorAccessibility3.js @@ -90,7 +90,7 @@ declare class Baz { } declare class Qux { x: number; - private constructor(x); + private constructor(); } declare let a: typeof Foo; declare let b: typeof Baz; diff --git a/tests/baselines/reference/classConstructorOverloadsAccessibility.js b/tests/baselines/reference/classConstructorOverloadsAccessibility.js index 7fef7443c62..2a173966d5d 100644 --- a/tests/baselines/reference/classConstructorOverloadsAccessibility.js +++ b/tests/baselines/reference/classConstructorOverloadsAccessibility.js @@ -59,7 +59,7 @@ var D = (function () { declare class A { constructor(a: boolean); protected constructor(a: number); - private constructor(a); + private constructor(); } declare class B { protected constructor(a: number); diff --git a/tests/baselines/reference/classExtendingPrimitive.errors.txt b/tests/baselines/reference/classExtendingPrimitive.errors.txt index 554e0fbecbc..32a3e68cb3e 100644 --- a/tests/baselines/reference/classExtendingPrimitive.errors.txt +++ b/tests/baselines/reference/classExtendingPrimitive.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(3,17): error TS2304: Cannot find name 'number'. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(4,18): error TS2304: Cannot find name 'string'. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(5,18): error TS2304: Cannot find name 'boolean'. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(3,17): error TS2693: 'number' only refers to a type, but is being used as a value here. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(4,18): error TS2693: 'string' only refers to a type, but is being used as a value here. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(5,18): error TS2693: 'boolean' only refers to a type, but is being used as a value here. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(6,18): error TS2304: Cannot find name 'Void'. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(7,19): error TS1109: Expression expected. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(8,18): error TS2304: Cannot find name 'Null'. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(10,18): error TS2507: Type 'undefined' is not a constructor function type. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(11,18): error TS2304: Cannot find name 'Undefined'. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(11,18): error TS2552: Cannot find name 'Undefined'. Did you mean 'undefined'? tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(14,18): error TS2507: Type 'typeof E' is not a constructor function type. @@ -14,13 +14,13 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla class C extends number { } ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. class C2 extends string { } ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. class C3 extends boolean { } ~~~~~~~ -!!! error TS2304: Cannot find name 'boolean'. +!!! error TS2693: 'boolean' only refers to a type, but is being used as a value here. class C4 extends Void { } ~~~~ !!! error TS2304: Cannot find name 'Void'. @@ -36,7 +36,7 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla !!! error TS2507: Type 'undefined' is not a constructor function type. class C7 extends Undefined { } ~~~~~~~~~ -!!! error TS2304: Cannot find name 'Undefined'. +!!! error TS2552: Cannot find name 'Undefined'. Did you mean 'undefined'? enum E { A } class C8 extends E { } diff --git a/tests/baselines/reference/classExtendsEveryObjectType.errors.txt b/tests/baselines/reference/classExtendsEveryObjectType.errors.txt index e1c5137e3a9..b4e8aa7360e 100644 --- a/tests/baselines/reference/classExtendsEveryObjectType.errors.txt +++ b/tests/baselines/reference/classExtendsEveryObjectType.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(4,17): error TS2689: Cannot extend an interface 'I'. Did you mean 'implements'? tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,18): error TS2507: Type '{ foo: any; }' is not a constructor function type. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,25): error TS2304: Cannot find name 'string'. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,25): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,31): error TS1005: ',' expected. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(8,18): error TS2507: Type '{ foo: string; }' is not a constructor function type. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(11,18): error TS2507: Type 'typeof M' is not a constructor function type. @@ -20,7 +20,7 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla ~~~~~~~~~~~~~~~~ !!! error TS2507: Type '{ foo: any; }' is not a constructor function type. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ',' expected. var x: { foo: string; } diff --git a/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt b/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt index af52a248b54..bbaac166582 100644 --- a/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt +++ b/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,18): error TS2507: Type '{ foo: any; }' is not a constructor function type. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,25): error TS2304: Cannot find name 'string'. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,25): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,31): error TS1005: ',' expected. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(3,18): error TS2507: Type 'undefined[]' is not a constructor function type. @@ -9,7 +9,7 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla ~~~~~~~~~~~~~~~~ !!! error TS2507: Type '{ foo: any; }' is not a constructor function type. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ',' expected. diff --git a/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt b/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt index b21e062e3b0..9854a115aa6 100644 --- a/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt +++ b/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt @@ -2,7 +2,7 @@ tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,11): error TS1146: D tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,12): error TS1005: '=' expected. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,14): error TS2304: Cannot find name 'name'. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,18): error TS1005: ']' expected. -tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,19): error TS2304: Cannot find name 'string'. +tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,19): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,25): error TS1005: ',' expected. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,26): error TS1136: Property assignment expected. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,27): error TS2304: Cannot find name 'VariableDeclaration'. @@ -20,7 +20,7 @@ tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,27): error TS2304: C ~ !!! error TS1005: ']' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ',' expected. ~ diff --git a/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt b/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt index 75f24d8c45a..da4c3a16f8b 100644 --- a/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt +++ b/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(10,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(22,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(31,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(39,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(10,9): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(22,9): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(31,10): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(39,10): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts (4 errors) ==== @@ -16,7 +16,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var r = C; var c = new C(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var c2 = new C(1); // ok class Base2 { @@ -30,7 +30,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var r2 = D; var d = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var d2 = new D(1); // ok // specialized base class @@ -41,7 +41,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var r3 = D2; var d3 = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var d4 = new D(1); // ok class D3 extends Base2 { @@ -51,5 +51,5 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var r4 = D3; var d5 = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var d6 = new D(1); // ok \ No newline at end of file diff --git a/tests/baselines/reference/classWithConstructors.errors.txt b/tests/baselines/reference/classWithConstructors.errors.txt index 61e0b1248b1..870d8ef13da 100644 --- a/tests/baselines/reference/classWithConstructors.errors.txt +++ b/tests/baselines/reference/classWithConstructors.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(6,13): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(15,14): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(21,13): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(31,13): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(40,14): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(46,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(6,13): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(15,14): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(21,13): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(31,13): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(40,14): error TS2554: Expected 1-2 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(46,13): error TS2554: Expected 1-2 arguments, but got 0. ==== tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts (6 errors) ==== @@ -14,7 +14,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c = new C(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var c2 = new C(''); // ok class C2 { @@ -25,7 +25,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c3 = new C2(); // error ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var c4 = new C2(''); // ok var c5 = new C2(1); // ok @@ -33,7 +33,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var d = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var d2 = new D(1); // ok var d3 = new D(''); // ok } @@ -45,7 +45,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c = new C(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var c2 = new C(''); // ok class C2 { @@ -56,7 +56,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c3 = new C2(); // error ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 0. var c4 = new C2(''); // ok var c5 = new C2(1, 2); // ok @@ -64,7 +64,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var d = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 0. var d2 = new D(1); // ok var d3 = new D(''); // ok } \ No newline at end of file diff --git a/tests/baselines/reference/classWithoutExplicitConstructor.errors.txt b/tests/baselines/reference/classWithoutExplicitConstructor.errors.txt index 981f38f017c..4064a1a11e3 100644 --- a/tests/baselines/reference/classWithoutExplicitConstructor.errors.txt +++ b/tests/baselines/reference/classWithoutExplicitConstructor.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts(7,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts(15,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts(7,10): error TS2554: Expected 0 arguments, but got 1. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts(15,10): error TS2554: Expected 0 arguments, but got 1. ==== tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts (2 errors) ==== @@ -11,7 +11,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/cl var c = new C(); var c2 = new C(null); // error ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. class D { x = 2 @@ -21,4 +21,4 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/cl var d = new D(); var d2 = new D(null); // error ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2554: Expected 0 arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/cloduleTest2.errors.txt b/tests/baselines/reference/cloduleTest2.errors.txt index 9659b5b0d4c..6a3c763ee58 100644 --- a/tests/baselines/reference/cloduleTest2.errors.txt +++ b/tests/baselines/reference/cloduleTest2.errors.txt @@ -1,11 +1,11 @@ -tests/cases/compiler/cloduleTest2.ts(4,13): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/cloduleTest2.ts(10,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/cloduleTest2.ts(4,13): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/cloduleTest2.ts(10,13): error TS2554: Expected 1 arguments, but got 0. tests/cases/compiler/cloduleTest2.ts(18,7): error TS2339: Property 'bar' does not exist on type 'm3d'. tests/cases/compiler/cloduleTest2.ts(19,7): error TS2339: Property 'y' does not exist on type 'm3d'. tests/cases/compiler/cloduleTest2.ts(27,7): error TS2339: Property 'bar' does not exist on type 'm3d'. tests/cases/compiler/cloduleTest2.ts(28,7): error TS2339: Property 'y' does not exist on type 'm3d'. -tests/cases/compiler/cloduleTest2.ts(33,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/cloduleTest2.ts(36,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/cloduleTest2.ts(33,9): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/cloduleTest2.ts(36,10): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/cloduleTest2.ts (8 errors) ==== @@ -14,7 +14,7 @@ tests/cases/compiler/cloduleTest2.ts(36,10): error TS2346: Supplied parameters d declare class m3d { constructor(foo); foo(): void ; static bar(); } var r = new m3d(); // error ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. } module T2 { @@ -22,7 +22,7 @@ tests/cases/compiler/cloduleTest2.ts(36,10): error TS2346: Supplied parameters d module m3d { export var y = 2; } var r = new m3d(); // error ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. } module T3 { @@ -55,9 +55,9 @@ tests/cases/compiler/cloduleTest2.ts(36,10): error TS2346: Supplied parameters d declare class m3d { constructor(foo); foo(): void; static bar(); } var r = new m3d(); // error ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. declare class m4d extends m3d { } var r2 = new m4d(); // error ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/collisionArgumentsClassConstructor.errors.txt b/tests/baselines/reference/collisionArgumentsClassConstructor.errors.txt index 03bf4f9e38b..a7066fb1fbe 100644 --- a/tests/baselines/reference/collisionArgumentsClassConstructor.errors.txt +++ b/tests/baselines/reference/collisionArgumentsClassConstructor.errors.txt @@ -13,9 +13,6 @@ tests/cases/compiler/collisionArgumentsClassConstructor.ts(30,24): error TS1210: tests/cases/compiler/collisionArgumentsClassConstructor.ts(31,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(35,24): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(36,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(41,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(44,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(47,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(51,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(52,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(53,25): error TS2396: Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters. @@ -30,15 +27,9 @@ tests/cases/compiler/collisionArgumentsClassConstructor.ts(67,17): error TS1210: tests/cases/compiler/collisionArgumentsClassConstructor.ts(68,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(69,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(70,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(75,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(76,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(79,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(80,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(84,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(85,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -==== tests/cases/compiler/collisionArgumentsClassConstructor.ts (38 errors) ==== +==== tests/cases/compiler/collisionArgumentsClassConstructor.ts (29 errors) ==== // Constructors class c1 { constructor(i: number, ...arguments) { // error @@ -110,18 +101,12 @@ tests/cases/compiler/collisionArgumentsClassConstructor.ts(85,17): error TS1210: declare class c4 { constructor(i: number, ...arguments); // No error - no code gen - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } declare class c42 { constructor(arguments: number, ...rest); // No error - no code gen - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } declare class c4NoError { constructor(arguments: number); // no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } class c5 { @@ -178,26 +163,14 @@ tests/cases/compiler/collisionArgumentsClassConstructor.ts(85,17): error TS1210: declare class c6 { constructor(i: number, ...arguments); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. constructor(i: string, ...arguments); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } declare class c62 { constructor(arguments: number, ...rest); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. constructor(arguments: string, ...rest); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } declare class c6NoError { constructor(arguments: number); // no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. constructor(arguments: string); // no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } \ No newline at end of file diff --git a/tests/baselines/reference/collisionArgumentsClassMethod.errors.txt b/tests/baselines/reference/collisionArgumentsClassMethod.errors.txt index ea699414f17..ec0562f57ca 100644 --- a/tests/baselines/reference/collisionArgumentsClassMethod.errors.txt +++ b/tests/baselines/reference/collisionArgumentsClassMethod.errors.txt @@ -20,20 +20,11 @@ tests/cases/compiler/collisionArgumentsClassMethod.ts(21,22): error TS1210: Inva tests/cases/compiler/collisionArgumentsClassMethod.ts(22,22): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassMethod.ts(23,22): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassMethod.ts(24,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(29,30): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(30,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(31,23): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(33,29): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(34,29): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(35,16): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(36,16): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(37,22): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(38,22): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassMethod.ts(43,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassMethod.ts(46,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -==== tests/cases/compiler/collisionArgumentsClassMethod.ts (33 errors) ==== +==== tests/cases/compiler/collisionArgumentsClassMethod.ts (24 errors) ==== class c1 { public foo(i: number, ...arguments) { //arguments is error ~~~~~~~~~~~~ @@ -107,33 +98,15 @@ tests/cases/compiler/collisionArgumentsClassMethod.ts(46,13): error TS1210: Inva declare class c2 { public foo(i: number, ...arguments); // No error - no code gen - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public foo1(arguments: number, ...rest); // No error - no code gen - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public fooNoError(arguments: number); // No error - no code gen - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public f4(i: number, ...arguments); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public f4(i: string, ...arguments); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public f41(arguments: number, ...rest); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public f41(arguments: string, ...rest); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public f4NoError(arguments: number); // no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public f4NoError(arguments: string); // no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } class c3 { diff --git a/tests/baselines/reference/commentEmittingInPreserveJsx1.js b/tests/baselines/reference/commentEmittingInPreserveJsx1.js new file mode 100644 index 00000000000..45e2148e007 --- /dev/null +++ b/tests/baselines/reference/commentEmittingInPreserveJsx1.js @@ -0,0 +1,57 @@ +//// [file.tsx] +import React = require('react'); + +
+ // Not Comment +
; + +
+ // Not Comment + { + //Comment just Fine + } + // Another not Comment +
; + +
+ // Not Comment + { + //Comment just Fine + "Hi" + } + // Another not Comment +
; + +
+ /* Not Comment */ + { + //Comment just Fine + "Hi" + } +
; + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +
+ // Not Comment +
; +
+ // Not Comment + + // Another not Comment +
; +
+ // Not Comment + { +//Comment just Fine +"Hi"} + // Another not Comment +
; +
+ /* Not Comment */ + { +//Comment just Fine +"Hi"} +
; diff --git a/tests/baselines/reference/commentEmittingInPreserveJsx1.symbols b/tests/baselines/reference/commentEmittingInPreserveJsx1.symbols new file mode 100644 index 00000000000..43d833e27b1 --- /dev/null +++ b/tests/baselines/reference/commentEmittingInPreserveJsx1.symbols @@ -0,0 +1,45 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + + // Not Comment +
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + + // Not Comment + { + //Comment just Fine + } + // Another not Comment +
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + + // Not Comment + { + //Comment just Fine + "Hi" + } + // Another not Comment +
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + + /* Not Comment */ + { + //Comment just Fine + "Hi" + } +
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + diff --git a/tests/baselines/reference/commentEmittingInPreserveJsx1.types b/tests/baselines/reference/commentEmittingInPreserveJsx1.types new file mode 100644 index 00000000000..2e968033d4c --- /dev/null +++ b/tests/baselines/reference/commentEmittingInPreserveJsx1.types @@ -0,0 +1,51 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +
+>
// Not Comment
: JSX.Element +>div : any + + // Not Comment +
; +>div : any + +
+>
// Not Comment { //Comment just Fine } // Another not Comment
: JSX.Element +>div : any + + // Not Comment + { + //Comment just Fine + } + // Another not Comment +
; +>div : any + +
+>
// Not Comment { //Comment just Fine "Hi" } // Another not Comment
: JSX.Element +>div : any + + // Not Comment + { + //Comment just Fine + "Hi" +>"Hi" : "Hi" + } + // Another not Comment +
; +>div : any + +
+>
/* Not Comment */ { //Comment just Fine "Hi" }
: JSX.Element +>div : any + + /* Not Comment */ + { + //Comment just Fine + "Hi" +>"Hi" : "Hi" + } +
; +>div : any + diff --git a/tests/baselines/reference/commentsAfterCaseClauses1.js b/tests/baselines/reference/commentsAfterCaseClauses1.js new file mode 100644 index 00000000000..e12fe703335 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses1.js @@ -0,0 +1,31 @@ +//// [commentsAfterCaseClauses1.ts] +function getSecurity(level) { + switch(level){ + case 0: // Zero + case 1: // one + case 2: // two + return "Hi"; + case 3: // three + case 4 : // four + return "hello"; + case 5: // five + default: // default + return "world"; + } +} + +//// [commentsAfterCaseClauses1.js] +function getSecurity(level) { + switch (level) { + case 0: // Zero + case 1: // one + case 2:// two + return "Hi"; + case 3: // three + case 4:// four + return "hello"; + case 5: // five + default:// default + return "world"; + } +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses1.symbols b/tests/baselines/reference/commentsAfterCaseClauses1.symbols new file mode 100644 index 00000000000..1ca620c4eb4 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses1.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/commentsAfterCaseClauses1.ts === +function getSecurity(level) { +>getSecurity : Symbol(getSecurity, Decl(commentsAfterCaseClauses1.ts, 0, 0)) +>level : Symbol(level, Decl(commentsAfterCaseClauses1.ts, 0, 21)) + + switch(level){ +>level : Symbol(level, Decl(commentsAfterCaseClauses1.ts, 0, 21)) + + case 0: // Zero + case 1: // one + case 2: // two + return "Hi"; + case 3: // three + case 4 : // four + return "hello"; + case 5: // five + default: // default + return "world"; + } +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses1.types b/tests/baselines/reference/commentsAfterCaseClauses1.types new file mode 100644 index 00000000000..c7759f1c2e6 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses1.types @@ -0,0 +1,37 @@ +=== tests/cases/compiler/commentsAfterCaseClauses1.ts === +function getSecurity(level) { +>getSecurity : (level: any) => "Hi" | "hello" | "world" +>level : any + + switch(level){ +>level : any + + case 0: // Zero +>0 : 0 + + case 1: // one +>1 : 1 + + case 2: // two +>2 : 2 + + return "Hi"; +>"Hi" : "Hi" + + case 3: // three +>3 : 3 + + case 4 : // four +>4 : 4 + + return "hello"; +>"hello" : "hello" + + case 5: // five +>5 : 5 + + default: // default + return "world"; +>"world" : "world" + } +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses2.js b/tests/baselines/reference/commentsAfterCaseClauses2.js new file mode 100644 index 00000000000..44cd3c0da74 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses2.js @@ -0,0 +1,36 @@ +//// [commentsAfterCaseClauses2.ts] +function getSecurity(level) { + switch(level){ + case 0: // Zero + case 1: // one + case 2: // two + // Leading comments + return "Hi"; + case 3: // three + case 4: // four + return "hello"; + case 5: // five + default: // default + return "world"; + // Comment After + } /*Comment 1*/ // Comment After 1 + // Comment After 2 +} + +//// [commentsAfterCaseClauses2.js] +function getSecurity(level) { + switch (level) { + case 0: // Zero + case 1: // one + case 2:// two + // Leading comments + return "Hi"; + case 3: // three + case 4:// four + return "hello"; + case 5: // five + default:// default + return "world"; + } /*Comment 1*/ // Comment After 1 + // Comment After 2 +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses2.symbols b/tests/baselines/reference/commentsAfterCaseClauses2.symbols new file mode 100644 index 00000000000..b68cf18c1b9 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses2.symbols @@ -0,0 +1,23 @@ +=== tests/cases/compiler/commentsAfterCaseClauses2.ts === +function getSecurity(level) { +>getSecurity : Symbol(getSecurity, Decl(commentsAfterCaseClauses2.ts, 0, 0)) +>level : Symbol(level, Decl(commentsAfterCaseClauses2.ts, 0, 21)) + + switch(level){ +>level : Symbol(level, Decl(commentsAfterCaseClauses2.ts, 0, 21)) + + case 0: // Zero + case 1: // one + case 2: // two + // Leading comments + return "Hi"; + case 3: // three + case 4: // four + return "hello"; + case 5: // five + default: // default + return "world"; + // Comment After + } /*Comment 1*/ // Comment After 1 + // Comment After 2 +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses2.types b/tests/baselines/reference/commentsAfterCaseClauses2.types new file mode 100644 index 00000000000..3b2d2e7688a --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses2.types @@ -0,0 +1,41 @@ +=== tests/cases/compiler/commentsAfterCaseClauses2.ts === +function getSecurity(level) { +>getSecurity : (level: any) => "Hi" | "hello" | "world" +>level : any + + switch(level){ +>level : any + + case 0: // Zero +>0 : 0 + + case 1: // one +>1 : 1 + + case 2: // two +>2 : 2 + + // Leading comments + return "Hi"; +>"Hi" : "Hi" + + case 3: // three +>3 : 3 + + case 4: // four +>4 : 4 + + return "hello"; +>"hello" : "hello" + + case 5: // five +>5 : 5 + + default: // default + return "world"; +>"world" : "world" + + // Comment After + } /*Comment 1*/ // Comment After 1 + // Comment After 2 +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses3.js b/tests/baselines/reference/commentsAfterCaseClauses3.js new file mode 100644 index 00000000000..9538ad06c4f --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses3.js @@ -0,0 +1,34 @@ +//// [commentsAfterCaseClauses3.ts] +function getSecurity(level) { + switch(level){ + case 0: /*Zero*/ + case 1: /*One*/ + case 2: /*two*/ + // Leading comments + return "Hi"; + case 3: /*three*/ + case 4: /*four*/ + return "hello"; + case 5: /*five*/ + default: /*six*/ + return "world"; + } + +} + +//// [commentsAfterCaseClauses3.js] +function getSecurity(level) { + switch (level) { + case 0: /*Zero*/ + case 1: /*One*/ + case 2:/*two*/ + // Leading comments + return "Hi"; + case 3: /*three*/ + case 4:/*four*/ + return "hello"; + case 5: /*five*/ + default:/*six*/ + return "world"; + } +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses3.symbols b/tests/baselines/reference/commentsAfterCaseClauses3.symbols new file mode 100644 index 00000000000..73151cffdd8 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses3.symbols @@ -0,0 +1,22 @@ +=== tests/cases/compiler/commentsAfterCaseClauses3.ts === +function getSecurity(level) { +>getSecurity : Symbol(getSecurity, Decl(commentsAfterCaseClauses3.ts, 0, 0)) +>level : Symbol(level, Decl(commentsAfterCaseClauses3.ts, 0, 21)) + + switch(level){ +>level : Symbol(level, Decl(commentsAfterCaseClauses3.ts, 0, 21)) + + case 0: /*Zero*/ + case 1: /*One*/ + case 2: /*two*/ + // Leading comments + return "Hi"; + case 3: /*three*/ + case 4: /*four*/ + return "hello"; + case 5: /*five*/ + default: /*six*/ + return "world"; + } + +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses3.types b/tests/baselines/reference/commentsAfterCaseClauses3.types new file mode 100644 index 00000000000..556370f4395 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses3.types @@ -0,0 +1,39 @@ +=== tests/cases/compiler/commentsAfterCaseClauses3.ts === +function getSecurity(level) { +>getSecurity : (level: any) => "Hi" | "hello" | "world" +>level : any + + switch(level){ +>level : any + + case 0: /*Zero*/ +>0 : 0 + + case 1: /*One*/ +>1 : 1 + + case 2: /*two*/ +>2 : 2 + + // Leading comments + return "Hi"; +>"Hi" : "Hi" + + case 3: /*three*/ +>3 : 3 + + case 4: /*four*/ +>4 : 4 + + return "hello"; +>"hello" : "hello" + + case 5: /*five*/ +>5 : 5 + + default: /*six*/ + return "world"; +>"world" : "world" + } + +} diff --git a/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt b/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt index a70eb0e5e2c..f149bce5080 100644 --- a/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt +++ b/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(1,7): error TS2506: 'S18' is referenced directly or indirectly in its own base expression. -tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(4,2): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(4,2): error TS2554: Expected 0 arguments, but got 1. ==== tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts (2 errors) ==== @@ -10,5 +10,5 @@ tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(4,2): erro } (new S18(123)).S18 = 0; ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/complicatedPrivacy.errors.txt b/tests/baselines/reference/complicatedPrivacy.errors.txt index c81605a5a83..661b0693807 100644 --- a/tests/baselines/reference/complicatedPrivacy.errors.txt +++ b/tests/baselines/reference/complicatedPrivacy.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/complicatedPrivacy.ts(11,24): error TS1054: A 'get' accessor cannot have parameters. tests/cases/compiler/complicatedPrivacy.ts(35,5): error TS1170: A computed property name in a type literal must directly refer to a built-in symbol. -tests/cases/compiler/complicatedPrivacy.ts(35,6): error TS2304: Cannot find name 'number'. +tests/cases/compiler/complicatedPrivacy.ts(35,6): error TS2693: 'number' only refers to a type, but is being used as a value here. tests/cases/compiler/complicatedPrivacy.ts(73,55): error TS2694: Namespace 'mglo5' has no exported member 'i6'. @@ -45,7 +45,7 @@ tests/cases/compiler/complicatedPrivacy.ts(73,55): error TS2694: Namespace 'mglo ~~~~~~~~ !!! error TS1170: A computed property name in a type literal must directly refer to a built-in symbol. ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. }) { } diff --git a/tests/baselines/reference/computedPropertyNames47_ES5.types b/tests/baselines/reference/computedPropertyNames47_ES5.types index 19811ae8ec2..137f3d63d38 100644 --- a/tests/baselines/reference/computedPropertyNames47_ES5.types +++ b/tests/baselines/reference/computedPropertyNames47_ES5.types @@ -12,7 +12,7 @@ var o = { >{ [E1.x || E2.x]: 0} : { [x: number]: number; } [E1.x || E2.x]: 0 ->E1.x || E2.x : E1 | E2 +>E1.x || E2.x : E2 >E1.x : E1 >E1 : typeof E1 >x : E1 diff --git a/tests/baselines/reference/computedPropertyNames47_ES6.types b/tests/baselines/reference/computedPropertyNames47_ES6.types index 46edecb450a..04c18df83a7 100644 --- a/tests/baselines/reference/computedPropertyNames47_ES6.types +++ b/tests/baselines/reference/computedPropertyNames47_ES6.types @@ -12,7 +12,7 @@ var o = { >{ [E1.x || E2.x]: 0} : { [x: number]: number; } [E1.x || E2.x]: 0 ->E1.x || E2.x : E1 | E2 +>E1.x || E2.x : E2 >E1.x : E1 >E1 : typeof E1 >x : E1 diff --git a/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt b/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt index 8a15123dfc8..265ce4686db 100644 --- a/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt +++ b/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts(9,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts(9,9): error TS2558: Expected 2 type arguments, but got 1. ==== tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts (1 errors) ==== @@ -12,5 +12,5 @@ tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts(9,9): error TS23 var d = new D(); ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2 type arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt index a572e0b34c8..1d37b20a3b3 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt @@ -52,13 +52,13 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,9): error TS tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,16): error TS2304: Cannot find name 'method1'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,24): error TS2304: Cannot find name 'val'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,27): error TS1005: ',' expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,28): error TS2304: Cannot find name 'number'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,28): error TS2693: 'number' only refers to a type, but is being used as a value here. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,36): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,9): error TS1128: Declaration or statement expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,16): error TS2304: Cannot find name 'method2'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,26): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(241,5): error TS1128: Declaration or statement expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(246,25): error TS2339: Property 'method1' does not exist on type 'B'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(246,25): error TS2551: Property 'method1' does not exist on type 'B'. Did you mean 'method2'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,9): error TS2390: Constructor implementation is missing. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,21): error TS2369: A parameter property is only allowed in a constructor implementation. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,44): error TS2369: A parameter property is only allowed in a constructor implementation. @@ -67,14 +67,14 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,9): error TS tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,16): error TS2304: Cannot find name 'Overloads'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,26): error TS2304: Cannot find name 'value'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,31): error TS1005: ',' expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,33): error TS2304: Cannot find name 'string'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,33): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,9): error TS1128: Declaration or statement expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,16): error TS2304: Cannot find name 'Overloads'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,27): error TS1135: Argument expression expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,33): error TS1005: '(' expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,35): error TS2304: Cannot find name 'string'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,35): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,43): error TS1109: Expression expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,52): error TS2304: Cannot find name 'string'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,52): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,60): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,65): error TS1109: Expression expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,9): error TS2304: Cannot find name 'public'. @@ -82,7 +82,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,16): error T tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,16): error TS2304: Cannot find name 'DefaultValue'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,29): error TS2304: Cannot find name 'value'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,35): error TS1109: Expression expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,37): error TS2304: Cannot find name 'string'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,37): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,55): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS1128: Declaration or statement expected. @@ -435,7 +435,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~ !!! error TS1005: ',' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. return val; @@ -458,7 +458,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS public method2() { return this.method1(2); ~~~~~~~ -!!! error TS2339: Property 'method1' does not exist on type 'B'. +!!! error TS2551: Property 'method1' does not exist on type 'B'. Did you mean 'method2'? } } @@ -486,7 +486,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~ !!! error TS1005: ',' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. public Overloads( while : string, ...rest: string[]) { & ~~~~~~ !!! error TS1128: Declaration or statement expected. @@ -497,11 +497,11 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~ !!! error TS1005: '(' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~~~ !!! error TS1109: Expression expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. ~ @@ -519,7 +519,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~ !!! error TS1109: Expression expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. } diff --git a/tests/baselines/reference/contextuallyTypedBindingInitializer.types b/tests/baselines/reference/contextuallyTypedBindingInitializer.types index e9624b156c7..4efd22a4c84 100644 --- a/tests/baselines/reference/contextuallyTypedBindingInitializer.types +++ b/tests/baselines/reference/contextuallyTypedBindingInitializer.types @@ -7,7 +7,7 @@ interface Show { >x : number } function f({ show = v => v.toString() }: Show) {} ->f : ({show}: Show) => void +>f : ({ show }: Show) => void >show : (x: number) => string >v => v.toString() : (v: number) => string >v : number @@ -18,7 +18,7 @@ function f({ show = v => v.toString() }: Show) {} >Show : Show function f2({ "show": showRename = v => v.toString() }: Show) {} ->f2 : ({"show": showRename}: Show) => void +>f2 : ({ "show": showRename }: Show) => void >showRename : (x: number) => string >v => v.toString() : (v: number) => string >v : number @@ -29,7 +29,7 @@ function f2({ "show": showRename = v => v.toString() }: Show) {} >Show : Show function f3({ ["show"]: showRename = v => v.toString() }: Show) {} ->f3 : ({["show"]: showRename}: Show) => void +>f3 : ({ ["show"]: showRename }: Show) => void >"show" : "show" >showRename : (x: number) => string >v => v.toString() : (v: number) => string @@ -48,7 +48,7 @@ interface Nested { >Show : Show } function ff({ nested = { show: v => v.toString() } }: Nested) {} ->ff : ({nested}: Nested) => void +>ff : ({ nested }: Nested) => void >nested : Show >{ show: v => v.toString() } : { show: (v: number) => string; } >show : (v: number) => string @@ -67,7 +67,7 @@ interface Tuples { >prop : [string, number] } function g({ prop = ["hello", 1234] }: Tuples) {} ->g : ({prop}: Tuples) => void +>g : ({ prop }: Tuples) => void >prop : [string, number] >["hello", 1234] : [string, number] >"hello" : "hello" @@ -81,7 +81,7 @@ interface StringUnion { >prop : "foo" | "bar" } function h({ prop = "foo" }: StringUnion) {} ->h : ({prop}: StringUnion) => void +>h : ({ prop }: StringUnion) => void >prop : "foo" | "bar" >"foo" : "foo" >StringUnion : StringUnion diff --git a/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.types b/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.types index 5adc82c3e62..1548e626e6d 100644 --- a/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.types +++ b/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.types @@ -7,7 +7,7 @@ interface Show { >x : number } function f({ show: showRename = v => v }: Show) {} ->f : ({show: showRename}: Show) => void +>f : ({ show: showRename }: Show) => void >show : any >showRename : ((x: number) => string) | ((v: number) => number) >v => v : (v: number) => number @@ -16,7 +16,7 @@ function f({ show: showRename = v => v }: Show) {} >Show : Show function f2({ "show": showRename = v => v }: Show) {} ->f2 : ({"show": showRename}: Show) => void +>f2 : ({ "show": showRename }: Show) => void >showRename : ((x: number) => string) | ((v: number) => number) >v => v : (v: number) => number >v : number @@ -24,7 +24,7 @@ function f2({ "show": showRename = v => v }: Show) {} >Show : Show function f3({ ["show"]: showRename = v => v }: Show) {} ->f3 : ({["show"]: showRename}: Show) => void +>f3 : ({ ["show"]: showRename }: Show) => void >"show" : "show" >showRename : ((x: number) => string) | ((v: number) => number) >v => v : (v: number) => number @@ -40,7 +40,7 @@ interface Nested { >Show : Show } function ff({ nested: nestedRename = { show: v => v } }: Nested) {} ->ff : ({nested: nestedRename}: Nested) => void +>ff : ({ nested: nestedRename }: Nested) => void >nested : any >nestedRename : Show | { show: (v: number) => number; } >{ show: v => v } : { show: (v: number) => number; } @@ -79,7 +79,7 @@ interface Tuples { >prop : [string, number] } function g({ prop = [101, 1234] }: Tuples) {} ->g : ({prop}: Tuples) => void +>g : ({ prop }: Tuples) => void >prop : [string, number] | [number, number] >[101, 1234] : [number, number] >101 : 101 @@ -93,7 +93,7 @@ interface StringUnion { >prop : "foo" | "bar" } function h({ prop = "baz" }: StringUnion) {} ->h : ({prop}: StringUnion) => void +>h : ({ prop }: StringUnion) => void >prop : "foo" | "bar" | "baz" >"baz" : "baz" >StringUnion : StringUnion diff --git a/tests/baselines/reference/contextuallyTypedIife.types b/tests/baselines/reference/contextuallyTypedIife.types index 04ddbf50fde..77bb40df903 100644 --- a/tests/baselines/reference/contextuallyTypedIife.types +++ b/tests/baselines/reference/contextuallyTypedIife.types @@ -175,8 +175,8 @@ // destructuring parameters (with defaults too!) (({ q }) => q)({ q : 13 }); >(({ q }) => q)({ q : 13 }) : number ->(({ q }) => q) : ({q}: { q: number; }) => number ->({ q }) => q : ({q}: { q: number; }) => number +>(({ q }) => q) : ({ q }: { q: number; }) => number +>({ q }) => q : ({ q }: { q: number; }) => number >q : number >q : number >{ q : 13 } : { q: number; } @@ -185,8 +185,8 @@ (({ p = 14 }) => p)({ p : 15 }); >(({ p = 14 }) => p)({ p : 15 }) : number ->(({ p = 14 }) => p) : ({p}: { p: number; }) => number ->({ p = 14 }) => p : ({p}: { p: number; }) => number +>(({ p = 14 }) => p) : ({ p }: { p: number; }) => number +>({ p = 14 }) => p : ({ p }: { p: number; }) => number >p : number >14 : 14 >p : number @@ -196,8 +196,8 @@ (({ r = 17 } = { r: 18 }) => r)({r : 19}); >(({ r = 17 } = { r: 18 }) => r)({r : 19}) : number ->(({ r = 17 } = { r: 18 }) => r) : ({r}?: { r: number; }) => number ->({ r = 17 } = { r: 18 }) => r : ({r}?: { r: number; }) => number +>(({ r = 17 } = { r: 18 }) => r) : ({ r }?: { r: number; }) => number +>({ r = 17 } = { r: 18 }) => r : ({ r }?: { r: number; }) => number >r : number >17 : 17 >{ r: 18 } : { r: number; } @@ -210,8 +210,8 @@ (({ u = 22 } = { u: 23 }) => u)(); >(({ u = 22 } = { u: 23 }) => u)() : number ->(({ u = 22 } = { u: 23 }) => u) : ({u}?: { u?: number; }) => number ->({ u = 22 } = { u: 23 }) => u : ({u}?: { u?: number; }) => number +>(({ u = 22 } = { u: 23 }) => u) : ({ u }?: { u?: number; }) => number +>({ u = 22 } = { u: 23 }) => u : ({ u }?: { u?: number; }) => number >u : number >22 : 22 >{ u: 23 } : { u?: number; } diff --git a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt index 28c550ccda1..ccf56532bc4 100644 --- a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt +++ b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt @@ -1,15 +1,13 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(27,24): error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'LinkProps'. + Property 'goTo' is missing in type '{ extra: true; onClick: (k: "left" | "right") => void; }'. tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(28,24): error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'onClick' does not exist on type 'IntrinsicAttributes & LinkProps'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(29,24): error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(30,24): error TS2322: Type '{ goTo: "home"; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(33,25): error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & ButtonProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,25): error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'LinkProps'. + Property 'goTo' is missing in type '{ onClick: (k: "left" | "right") => void; extra: true; }'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(29,43): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(30,36): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(33,65): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,44): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. ==== tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx (6 errors) ==== @@ -42,29 +40,27 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,25): err const b0 = {console.log(k)}}} extra />; // k has type "left" | "right" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. +!!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'LinkProps'. +!!! error TS2322: Property 'goTo' is missing in type '{ extra: true; onClick: (k: "left" | "right") => void; }'. const b2 = {console.log(k)}} extra />; // k has type "left" | "right" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & LinkProps'. +!!! error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'LinkProps'. +!!! error TS2322: Property 'goTo' is missing in type '{ onClick: (k: "left" | "right") => void; extra: true; }'. const b3 = ; // goTo has type"home" | "contact" - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + ~~~~~ +!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. const b4 = ; // goTo has type "home" | "contact" - ~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ goTo: "home"; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + ~~~~~ +!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. export function NoOverload(buttonProps: ButtonProps): JSX.Element { return undefined } const c1 = {console.log(k)}}} extra />; // k has type any - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & ButtonProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'. + ~~~~~ +!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'. export function NoOverload1(linkProps: LinkProps): JSX.Element { return undefined } const d1 = ; // goTo has type "home" | "contact" - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + ~~~~~ +!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. \ No newline at end of file diff --git a/tests/baselines/reference/controlFlowDestructuringParameters.types b/tests/baselines/reference/controlFlowDestructuringParameters.types index 7fdb1eded01..44755dca81b 100644 --- a/tests/baselines/reference/controlFlowDestructuringParameters.types +++ b/tests/baselines/reference/controlFlowDestructuringParameters.types @@ -12,7 +12,7 @@ >map : { (this: [{ x: number; }, { x: number; }, { x: number; }, { x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U): [U, U, U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }, { x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: undefined): [U, U, U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }, { x: number; }, { x: number; }], callbackfn: (this: Z, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: Z): [U, U, U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U): [U, U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: undefined): [U, U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }, { x: number; }], callbackfn: (this: Z, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: Z): [U, U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U): [U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: undefined): [U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }], callbackfn: (this: Z, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: Z): [U, U, U]; (this: [{ x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U): [U, U]; (this: [{ x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: undefined): [U, U]; (this: [{ x: number; }, { x: number; }], callbackfn: (this: Z, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: Z): [U, U]; (callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U): U[]; (callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: undefined): U[]; (callbackfn: (this: Z, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: Z): U[]; } ({ x }) => x ->({ x }) => x : (this: void, {x}: { x: number; }) => number +>({ x }) => x : (this: void, { x }: { x: number; }) => number >x : number >x : number diff --git a/tests/baselines/reference/couldNotSelectGenericOverload.errors.txt b/tests/baselines/reference/couldNotSelectGenericOverload.errors.txt index bafa2bc4237..c351245ef11 100644 --- a/tests/baselines/reference/couldNotSelectGenericOverload.errors.txt +++ b/tests/baselines/reference/couldNotSelectGenericOverload.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/couldNotSelectGenericOverload.ts(3,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/couldNotSelectGenericOverload.ts(7,11): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/couldNotSelectGenericOverload.ts(3,11): error TS2554: Expected 1 arguments, but got 2. +tests/cases/compiler/couldNotSelectGenericOverload.ts(7,11): error TS2554: Expected 1 arguments, but got 2. ==== tests/cases/compiler/couldNotSelectGenericOverload.ts (2 errors) ==== @@ -7,11 +7,11 @@ tests/cases/compiler/couldNotSelectGenericOverload.ts(7,11): error TS2346: Suppl var b = [1, ""]; var b1G = makeArray(1, ""); // any, no error ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. var b2G = makeArray(b); // any[] function makeArray2(items: any[]): any[] { return items; } var b3G = makeArray2(1, ""); // error ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. \ No newline at end of file diff --git a/tests/baselines/reference/createArray.errors.txt b/tests/baselines/reference/createArray.errors.txt index 31f6b880030..082e8dc03e2 100644 --- a/tests/baselines/reference/createArray.errors.txt +++ b/tests/baselines/reference/createArray.errors.txt @@ -1,16 +1,16 @@ -tests/cases/compiler/createArray.ts(1,12): error TS2304: Cannot find name 'number'. +tests/cases/compiler/createArray.ts(1,12): error TS2693: 'number' only refers to a type, but is being used as a value here. tests/cases/compiler/createArray.ts(1,18): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. tests/cases/compiler/createArray.ts(6,6): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/compiler/createArray.ts(7,12): error TS2304: Cannot find name 'boolean'. +tests/cases/compiler/createArray.ts(7,12): error TS2693: 'boolean' only refers to a type, but is being used as a value here. tests/cases/compiler/createArray.ts(7,19): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/compiler/createArray.ts(8,12): error TS2304: Cannot find name 'string'. +tests/cases/compiler/createArray.ts(8,12): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/createArray.ts(8,18): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. ==== tests/cases/compiler/createArray.ts (7 errors) ==== var na=new number[]; ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. @@ -22,12 +22,12 @@ tests/cases/compiler/createArray.ts(8,18): error TS1150: 'new T[]' cannot be use !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. var ba=new boolean[]; ~~~~~~~ -!!! error TS2304: Cannot find name 'boolean'. +!!! error TS2693: 'boolean' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. var sa=new string[]; ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. function f(s:string):number { return 0; diff --git a/tests/baselines/reference/declarationEmitBindingPatterns.types b/tests/baselines/reference/declarationEmitBindingPatterns.types index 1a47fbebf07..d49893dad94 100644 --- a/tests/baselines/reference/declarationEmitBindingPatterns.types +++ b/tests/baselines/reference/declarationEmitBindingPatterns.types @@ -1,7 +1,7 @@ === tests/cases/compiler/declarationEmitBindingPatterns.ts === const k = ({x: z = 'y'}) => { } ->k : ({x: z}: { x?: string; }) => void ->({x: z = 'y'}) => { } : ({x: z}: { x?: string; }) => void +>k : ({ x: z }: { x?: string; }) => void +>({x: z = 'y'}) => { } : ({ x: z }: { x?: string; }) => void >x : any >z : string >'y' : "y" @@ -10,7 +10,7 @@ var a; >a : any function f({} = a, [] = a, { p: {} = a} = a) { ->f : ({}?: any, []?: any, {p: {}}?: any) => void +>f : ({}?: any, []?: any, { p: {} }?: any) => void >a : any >a : any >p : any diff --git a/tests/baselines/reference/declarationEmitClassPrivateConstructor.js b/tests/baselines/reference/declarationEmitClassPrivateConstructor.js new file mode 100644 index 00000000000..6cc65964987 --- /dev/null +++ b/tests/baselines/reference/declarationEmitClassPrivateConstructor.js @@ -0,0 +1,72 @@ +//// [declarationEmitClassPrivateConstructor.ts] +interface PrivateInterface { +} + +export class ExportedClass1 { + private constructor(data: PrivateInterface) { } +} + +export class ExportedClass2 { + private constructor(private data: PrivateInterface) { } +} + +export class ExportedClass3 { + private constructor(private data: PrivateInterface, private n: number) { } +} + +export class ExportedClass4 { + private constructor(private data: PrivateInterface, public n:number) { } +} + +//// [declarationEmitClassPrivateConstructor.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var ExportedClass1 = (function () { + function ExportedClass1(data) { + } + return ExportedClass1; +}()); +exports.ExportedClass1 = ExportedClass1; +var ExportedClass2 = (function () { + function ExportedClass2(data) { + this.data = data; + } + return ExportedClass2; +}()); +exports.ExportedClass2 = ExportedClass2; +var ExportedClass3 = (function () { + function ExportedClass3(data, n) { + this.data = data; + this.n = n; + } + return ExportedClass3; +}()); +exports.ExportedClass3 = ExportedClass3; +var ExportedClass4 = (function () { + function ExportedClass4(data, n) { + this.data = data; + this.n = n; + } + return ExportedClass4; +}()); +exports.ExportedClass4 = ExportedClass4; + + +//// [declarationEmitClassPrivateConstructor.d.ts] +export declare class ExportedClass1 { + private constructor(); +} +export declare class ExportedClass2 { + private data; + private constructor(); +} +export declare class ExportedClass3 { + private data; + private n; + private constructor(); +} +export declare class ExportedClass4 { + private data; + n: number; + private constructor(); +} diff --git a/tests/baselines/reference/declarationEmitClassPrivateConstructor.symbols b/tests/baselines/reference/declarationEmitClassPrivateConstructor.symbols new file mode 100644 index 00000000000..285d9fb3f39 --- /dev/null +++ b/tests/baselines/reference/declarationEmitClassPrivateConstructor.symbols @@ -0,0 +1,38 @@ +=== tests/cases/compiler/declarationEmitClassPrivateConstructor.ts === +interface PrivateInterface { +>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0)) +} + +export class ExportedClass1 { +>ExportedClass1 : Symbol(ExportedClass1, Decl(declarationEmitClassPrivateConstructor.ts, 1, 1)) + + private constructor(data: PrivateInterface) { } +>data : Symbol(data, Decl(declarationEmitClassPrivateConstructor.ts, 4, 24)) +>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0)) +} + +export class ExportedClass2 { +>ExportedClass2 : Symbol(ExportedClass2, Decl(declarationEmitClassPrivateConstructor.ts, 5, 1)) + + private constructor(private data: PrivateInterface) { } +>data : Symbol(ExportedClass2.data, Decl(declarationEmitClassPrivateConstructor.ts, 8, 24)) +>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0)) +} + +export class ExportedClass3 { +>ExportedClass3 : Symbol(ExportedClass3, Decl(declarationEmitClassPrivateConstructor.ts, 9, 1)) + + private constructor(private data: PrivateInterface, private n: number) { } +>data : Symbol(ExportedClass3.data, Decl(declarationEmitClassPrivateConstructor.ts, 12, 24)) +>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0)) +>n : Symbol(ExportedClass3.n, Decl(declarationEmitClassPrivateConstructor.ts, 12, 55)) +} + +export class ExportedClass4 { +>ExportedClass4 : Symbol(ExportedClass4, Decl(declarationEmitClassPrivateConstructor.ts, 13, 1)) + + private constructor(private data: PrivateInterface, public n:number) { } +>data : Symbol(ExportedClass4.data, Decl(declarationEmitClassPrivateConstructor.ts, 16, 24)) +>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0)) +>n : Symbol(ExportedClass4.n, Decl(declarationEmitClassPrivateConstructor.ts, 16, 55)) +} diff --git a/tests/baselines/reference/declarationEmitClassPrivateConstructor.types b/tests/baselines/reference/declarationEmitClassPrivateConstructor.types new file mode 100644 index 00000000000..ed8d5494ba6 --- /dev/null +++ b/tests/baselines/reference/declarationEmitClassPrivateConstructor.types @@ -0,0 +1,38 @@ +=== tests/cases/compiler/declarationEmitClassPrivateConstructor.ts === +interface PrivateInterface { +>PrivateInterface : PrivateInterface +} + +export class ExportedClass1 { +>ExportedClass1 : ExportedClass1 + + private constructor(data: PrivateInterface) { } +>data : PrivateInterface +>PrivateInterface : PrivateInterface +} + +export class ExportedClass2 { +>ExportedClass2 : ExportedClass2 + + private constructor(private data: PrivateInterface) { } +>data : PrivateInterface +>PrivateInterface : PrivateInterface +} + +export class ExportedClass3 { +>ExportedClass3 : ExportedClass3 + + private constructor(private data: PrivateInterface, private n: number) { } +>data : PrivateInterface +>PrivateInterface : PrivateInterface +>n : number +} + +export class ExportedClass4 { +>ExportedClass4 : ExportedClass4 + + private constructor(private data: PrivateInterface, public n:number) { } +>data : PrivateInterface +>PrivateInterface : PrivateInterface +>n : number +} diff --git a/tests/baselines/reference/declarationEmitClassPrivateConstructor2.errors.txt b/tests/baselines/reference/declarationEmitClassPrivateConstructor2.errors.txt new file mode 100644 index 00000000000..a31454a4760 --- /dev/null +++ b/tests/baselines/reference/declarationEmitClassPrivateConstructor2.errors.txt @@ -0,0 +1,20 @@ +tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts(5,38): error TS4031: Public property 'data' of exported class has or is using private name 'PrivateInterface'. +tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts(10,33): error TS4063: Parameter 'data' of constructor from exported class has or is using private name 'PrivateInterface'. + + +==== tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts (2 errors) ==== + interface PrivateInterface { + } + + export class ExportedClass1 { + private constructor(public data: PrivateInterface) { } + ~~~~~~~~~~~~~~~~ +!!! error TS4031: Public property 'data' of exported class has or is using private name 'PrivateInterface'. + } + + + export class ExportedClass2 { + protected constructor(data: PrivateInterface) { } + ~~~~~~~~~~~~~~~~ +!!! error TS4063: Parameter 'data' of constructor from exported class has or is using private name 'PrivateInterface'. + } \ No newline at end of file diff --git a/tests/baselines/reference/declarationEmitClassPrivateConstructor2.js b/tests/baselines/reference/declarationEmitClassPrivateConstructor2.js new file mode 100644 index 00000000000..8b7ad25a6bf --- /dev/null +++ b/tests/baselines/reference/declarationEmitClassPrivateConstructor2.js @@ -0,0 +1,29 @@ +//// [declarationEmitClassPrivateConstructor2.ts] +interface PrivateInterface { +} + +export class ExportedClass1 { + private constructor(public data: PrivateInterface) { } +} + + +export class ExportedClass2 { + protected constructor(data: PrivateInterface) { } +} + +//// [declarationEmitClassPrivateConstructor2.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var ExportedClass1 = (function () { + function ExportedClass1(data) { + this.data = data; + } + return ExportedClass1; +}()); +exports.ExportedClass1 = ExportedClass1; +var ExportedClass2 = (function () { + function ExportedClass2(data) { + } + return ExportedClass2; +}()); +exports.ExportedClass2 = ExportedClass2; diff --git a/tests/baselines/reference/declarationEmitDefaultExport5.js b/tests/baselines/reference/declarationEmitDefaultExport5.js index 701318b14d7..427463be5ab 100644 --- a/tests/baselines/reference/declarationEmitDefaultExport5.js +++ b/tests/baselines/reference/declarationEmitDefaultExport5.js @@ -7,5 +7,5 @@ export default 1 + 2; //// [declarationEmitDefaultExport5.d.ts] -declare var _default: number; +declare const _default: number; export default _default; diff --git a/tests/baselines/reference/declarationEmitDefaultExport6.js b/tests/baselines/reference/declarationEmitDefaultExport6.js index d56609e8534..1391ec0b4f2 100644 --- a/tests/baselines/reference/declarationEmitDefaultExport6.js +++ b/tests/baselines/reference/declarationEmitDefaultExport6.js @@ -12,5 +12,5 @@ export default new A(); //// [declarationEmitDefaultExport6.d.ts] export declare class A { } -declare var _default: A; +declare const _default: A; export default _default; diff --git a/tests/baselines/reference/declarationEmitDefaultExport8.js b/tests/baselines/reference/declarationEmitDefaultExport8.js index 5511c5981e5..33ef87bf744 100644 --- a/tests/baselines/reference/declarationEmitDefaultExport8.js +++ b/tests/baselines/reference/declarationEmitDefaultExport8.js @@ -13,5 +13,5 @@ export default 1 + 2; //// [declarationEmitDefaultExport8.d.ts] declare var _default: number; export { _default as d }; -declare var _default_1: number; +declare const _default_1: number; export default _default_1; diff --git a/tests/baselines/reference/declarationEmitDefaultExportWithTempVarName.js b/tests/baselines/reference/declarationEmitDefaultExportWithTempVarName.js index 44e0560132f..11fddc855b2 100644 --- a/tests/baselines/reference/declarationEmitDefaultExportWithTempVarName.js +++ b/tests/baselines/reference/declarationEmitDefaultExportWithTempVarName.js @@ -15,5 +15,5 @@ System.register([], function (exports_1, context_1) { //// [pi.d.ts] -declare var _default: 3.14159; +declare const _default: 3.14159; export default _default; diff --git a/tests/baselines/reference/declarationEmitDefaultExportWithTempVarNameWithBundling.js b/tests/baselines/reference/declarationEmitDefaultExportWithTempVarNameWithBundling.js index 6ac6cf29018..31749d1773e 100644 --- a/tests/baselines/reference/declarationEmitDefaultExportWithTempVarNameWithBundling.js +++ b/tests/baselines/reference/declarationEmitDefaultExportWithTempVarNameWithBundling.js @@ -16,6 +16,6 @@ System.register("pi", [], function (exports_1, context_1) { //// [app.d.ts] declare module "pi" { - var _default: 3.14159; + const _default: 3.14159; export default _default; } diff --git a/tests/baselines/reference/declarationEmitDestructuring1.types b/tests/baselines/reference/declarationEmitDestructuring1.types index abba67981d8..161ad94e54a 100644 --- a/tests/baselines/reference/declarationEmitDestructuring1.types +++ b/tests/baselines/reference/declarationEmitDestructuring1.types @@ -12,7 +12,7 @@ function far([a, [b], [[c]]]: [number, boolean[], string[][]]): void { } >c : string function bar({a1, b1, c1}: { a1: number, b1: boolean, c1: string }): void { } ->bar : ({a1, b1, c1}: { a1: number; b1: boolean; c1: string; }) => void +>bar : ({ a1, b1, c1 }: { a1: number; b1: boolean; c1: string; }) => void >a1 : number >b1 : boolean >c1 : string @@ -21,7 +21,7 @@ function bar({a1, b1, c1}: { a1: number, b1: boolean, c1: string }): void { } >c1 : string function baz({a2, b2: {b1, c1}}: { a2: number, b2: { b1: boolean, c1: string } }): void { } ->baz : ({a2, b2: {b1, c1}}: { a2: number; b2: { b1: boolean; c1: string; }; }) => void +>baz : ({ a2, b2: { b1, c1 } }: { a2: number; b2: { b1: boolean; c1: string; }; }) => void >a2 : number >b2 : any >b1 : boolean diff --git a/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.types b/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.types index 0bf290bcf7d..fb8c57d019b 100644 --- a/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.types +++ b/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.types @@ -11,7 +11,7 @@ function foo(...rest: any[]) { } function foo2( { x, y, z }?: { x: string; y: number; z: boolean }); ->foo2 : ({x, y, z}?: { x: string; y: number; z: boolean; }) => any +>foo2 : ({ x, y, z }?: { x: string; y: number; z: boolean; }) => any >x : string >y : number >z : boolean @@ -20,7 +20,7 @@ function foo2( { x, y, z }?: { x: string; y: number; z: boolean }); >z : boolean function foo2(...rest: any[]) { ->foo2 : ({x, y, z}?: { x: string; y: number; z: boolean; }) => any +>foo2 : ({ x, y, z }?: { x: string; y: number; z: boolean; }) => any >rest : any[] } diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends2.js b/tests/baselines/reference/declarationEmitExpressionInExtends2.js index 301d935a1db..a49175a3dc4 100644 --- a/tests/baselines/reference/declarationEmitExpressionInExtends2.js +++ b/tests/baselines/reference/declarationEmitExpressionInExtends2.js @@ -45,5 +45,6 @@ declare class C { y: U; } declare function getClass(c: T): typeof C; -declare class MyClass extends C { +declare const MyClass_base: typeof C; +declare class MyClass extends MyClass_base { } diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends3.errors.txt b/tests/baselines/reference/declarationEmitExpressionInExtends3.errors.txt index 636085215ac..4864a3bcdc2 100644 --- a/tests/baselines/reference/declarationEmitExpressionInExtends3.errors.txt +++ b/tests/baselines/reference/declarationEmitExpressionInExtends3.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/declarationEmitExpressionInExtends3.ts(28,30): error TS4020: 'extends' clause of exported class 'MyClass' has or is using private name 'LocalClass'. -tests/cases/compiler/declarationEmitExpressionInExtends3.ts(36,31): error TS4020: 'extends' clause of exported class 'MyClass3' has or is using private name 'LocalInterface'. +tests/cases/compiler/declarationEmitExpressionInExtends3.ts(36,75): error TS4020: 'extends' clause of exported class 'MyClass3' has or is using private name 'LocalInterface'. ==== tests/cases/compiler/declarationEmitExpressionInExtends3.ts (2 errors) ==== @@ -41,7 +41,7 @@ tests/cases/compiler/declarationEmitExpressionInExtends3.ts(36,31): error TS4020 export class MyClass3 extends getExportedClass(undefined) { // Error LocalInterface is inaccisble - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~ !!! error TS4020: 'extends' clause of exported class 'MyClass3' has or is using private name 'LocalInterface'. } diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends4.errors.txt b/tests/baselines/reference/declarationEmitExpressionInExtends4.errors.txt index b2e3eb58d54..569e5aa355f 100644 --- a/tests/baselines/reference/declarationEmitExpressionInExtends4.errors.txt +++ b/tests/baselines/reference/declarationEmitExpressionInExtends4.errors.txt @@ -1,30 +1,21 @@ -tests/cases/compiler/declarationEmitExpressionInExtends4.ts(1,10): error TS4060: Return type of exported function has or is using private name 'D'. -tests/cases/compiler/declarationEmitExpressionInExtends4.ts(5,7): error TS4093: 'extends' clause of exported class 'C' refers to a type whose name cannot be referenced. tests/cases/compiler/declarationEmitExpressionInExtends4.ts(5,17): error TS2315: Type 'D' is not generic. -tests/cases/compiler/declarationEmitExpressionInExtends4.ts(9,7): error TS4093: 'extends' clause of exported class 'C2' refers to a type whose name cannot be referenced. tests/cases/compiler/declarationEmitExpressionInExtends4.ts(9,18): error TS2304: Cannot find name 'SomeUndefinedFunction'. tests/cases/compiler/declarationEmitExpressionInExtends4.ts(14,18): error TS2304: Cannot find name 'SomeUndefinedFunction'. tests/cases/compiler/declarationEmitExpressionInExtends4.ts(14,18): error TS4020: 'extends' clause of exported class 'C3' has or is using private name 'SomeUndefinedFunction'. -==== tests/cases/compiler/declarationEmitExpressionInExtends4.ts (7 errors) ==== +==== tests/cases/compiler/declarationEmitExpressionInExtends4.ts (4 errors) ==== function getSomething() { - ~~~~~~~~~~~~ -!!! error TS4060: Return type of exported function has or is using private name 'D'. return class D { } } class C extends getSomething() { - ~ -!!! error TS4093: 'extends' clause of exported class 'C' refers to a type whose name cannot be referenced. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2315: Type 'D' is not generic. } class C2 extends SomeUndefinedFunction() { - ~~ -!!! error TS4093: 'extends' clause of exported class 'C2' refers to a type whose name cannot be referenced. ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'SomeUndefinedFunction'. diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends5.js b/tests/baselines/reference/declarationEmitExpressionInExtends5.js new file mode 100644 index 00000000000..77f8fc0e12c --- /dev/null +++ b/tests/baselines/reference/declarationEmitExpressionInExtends5.js @@ -0,0 +1,67 @@ +//// [declarationEmitExpressionInExtends5.ts] +namespace Test +{ + export interface IFace + { + } + + export class SomeClass implements IFace + { + } + + export class Derived extends getClass() + { + } + + export function getClass() : new() => T + { + return SomeClass as (new() => T); + } +} + + +//// [declarationEmitExpressionInExtends5.js] +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var Test; +(function (Test) { + var SomeClass = (function () { + function SomeClass() { + } + return SomeClass; + }()); + Test.SomeClass = SomeClass; + var Derived = (function (_super) { + __extends(Derived, _super); + function Derived() { + return _super !== null && _super.apply(this, arguments) || this; + } + return Derived; + }(getClass())); + Test.Derived = Derived; + function getClass() { + return SomeClass; + } + Test.getClass = getClass; +})(Test || (Test = {})); + + +//// [declarationEmitExpressionInExtends5.d.ts] +declare namespace Test { + interface IFace { + } + class SomeClass implements IFace { + } + const Derived_base: new () => IFace; + class Derived extends Derived_base { + } + function getClass(): new () => T; +} diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends5.symbols b/tests/baselines/reference/declarationEmitExpressionInExtends5.symbols new file mode 100644 index 00000000000..42bf5892211 --- /dev/null +++ b/tests/baselines/reference/declarationEmitExpressionInExtends5.symbols @@ -0,0 +1,33 @@ +=== tests/cases/compiler/declarationEmitExpressionInExtends5.ts === +namespace Test +>Test : Symbol(Test, Decl(declarationEmitExpressionInExtends5.ts, 0, 0)) +{ + export interface IFace +>IFace : Symbol(IFace, Decl(declarationEmitExpressionInExtends5.ts, 1, 1)) + { + } + + export class SomeClass implements IFace +>SomeClass : Symbol(SomeClass, Decl(declarationEmitExpressionInExtends5.ts, 4, 2)) +>IFace : Symbol(IFace, Decl(declarationEmitExpressionInExtends5.ts, 1, 1)) + { + } + + export class Derived extends getClass() +>Derived : Symbol(Derived, Decl(declarationEmitExpressionInExtends5.ts, 8, 2)) +>getClass : Symbol(getClass, Decl(declarationEmitExpressionInExtends5.ts, 12, 2)) +>IFace : Symbol(IFace, Decl(declarationEmitExpressionInExtends5.ts, 1, 1)) + { + } + + export function getClass() : new() => T +>getClass : Symbol(getClass, Decl(declarationEmitExpressionInExtends5.ts, 12, 2)) +>T : Symbol(T, Decl(declarationEmitExpressionInExtends5.ts, 14, 26)) +>T : Symbol(T, Decl(declarationEmitExpressionInExtends5.ts, 14, 26)) + { + return SomeClass as (new() => T); +>SomeClass : Symbol(SomeClass, Decl(declarationEmitExpressionInExtends5.ts, 4, 2)) +>T : Symbol(T, Decl(declarationEmitExpressionInExtends5.ts, 14, 26)) + } +} + diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends5.types b/tests/baselines/reference/declarationEmitExpressionInExtends5.types new file mode 100644 index 00000000000..22aafb85e58 --- /dev/null +++ b/tests/baselines/reference/declarationEmitExpressionInExtends5.types @@ -0,0 +1,35 @@ +=== tests/cases/compiler/declarationEmitExpressionInExtends5.ts === +namespace Test +>Test : typeof Test +{ + export interface IFace +>IFace : IFace + { + } + + export class SomeClass implements IFace +>SomeClass : SomeClass +>IFace : IFace + { + } + + export class Derived extends getClass() +>Derived : Derived +>getClass() : IFace +>getClass : () => new () => T +>IFace : IFace + { + } + + export function getClass() : new() => T +>getClass : () => new () => T +>T : T +>T : T + { + return SomeClass as (new() => T); +>SomeClass as (new() => T) : new () => T +>SomeClass : typeof SomeClass +>T : T + } +} + diff --git a/tests/baselines/reference/declarationEmitInferedDefaultExportType.js b/tests/baselines/reference/declarationEmitInferedDefaultExportType.js index 4d9eb47641a..a9eca8d1161 100644 --- a/tests/baselines/reference/declarationEmitInferedDefaultExportType.js +++ b/tests/baselines/reference/declarationEmitInferedDefaultExportType.js @@ -18,7 +18,7 @@ exports["default"] = { //// [declarationEmitInferedDefaultExportType.d.ts] -declare var _default: { +declare const _default: { foo: any[]; bar: any; baz: any; diff --git a/tests/baselines/reference/declarationEmitInferedDefaultExportType2.js b/tests/baselines/reference/declarationEmitInferedDefaultExportType2.js index 96c16829d7e..fde31605659 100644 --- a/tests/baselines/reference/declarationEmitInferedDefaultExportType2.js +++ b/tests/baselines/reference/declarationEmitInferedDefaultExportType2.js @@ -16,7 +16,7 @@ module.exports = { //// [declarationEmitInferedDefaultExportType2.d.ts] -declare var _default: { +declare const _default: { foo: any[]; bar: any; baz: any; diff --git a/tests/baselines/reference/declarationEmitInvalidReference2.errors.txt b/tests/baselines/reference/declarationEmitInvalidReference2.errors.txt index 32423b8d849..cca1805ea35 100644 --- a/tests/baselines/reference/declarationEmitInvalidReference2.errors.txt +++ b/tests/baselines/reference/declarationEmitInvalidReference2.errors.txt @@ -1,8 +1,8 @@ -tests/cases/compiler/declarationEmitInvalidReference2.ts(1,1): error TS6053: File 'tests/cases/compiler/invalid.ts' not found. +tests/cases/compiler/declarationEmitInvalidReference2.ts(1,22): error TS6053: File 'tests/cases/compiler/invalid.ts' not found. ==== tests/cases/compiler/declarationEmitInvalidReference2.ts (1 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~ !!! error TS6053: File 'tests/cases/compiler/invalid.ts' not found. var x = 0; \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClass8.errors.txt b/tests/baselines/reference/decoratorOnClass8.errors.txt index f9ca7fca210..4c13520364b 100644 --- a/tests/baselines/reference/decoratorOnClass8.errors.txt +++ b/tests/baselines/reference/decoratorOnClass8.errors.txt @@ -1,5 +1,4 @@ tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1238: Unable to resolve signature of class decorator when called as an expression. - Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/decoratorOnClass8.ts (1 errors) ==== @@ -8,6 +7,5 @@ tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1238 @dec() ~~~~~~ !!! error TS1238: Unable to resolve signature of class decorator when called as an expression. -!!! error TS1238: Supplied parameters do not match any signature of call target. class C { } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod6.errors.txt b/tests/baselines/reference/decoratorOnClassMethod6.errors.txt index c8ee66717ef..530e86117ee 100644 --- a/tests/baselines/reference/decoratorOnClassMethod6.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethod6.errors.txt @@ -1,5 +1,4 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): error TS1241: Unable to resolve signature of method decorator when called as an expression. - Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts (1 errors) ==== @@ -9,5 +8,4 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): @dec ["method"]() {} ~~~~ !!! error TS1241: Unable to resolve signature of method decorator when called as an expression. -!!! error TS1241: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod8.errors.txt b/tests/baselines/reference/decoratorOnClassMethod8.errors.txt index f522dc01df9..3ada30296b6 100644 --- a/tests/baselines/reference/decoratorOnClassMethod8.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethod8.errors.txt @@ -1,5 +1,4 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): error TS1241: Unable to resolve signature of method decorator when called as an expression. - Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts (1 errors) ==== @@ -9,5 +8,4 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): @dec method() {} ~~~~ !!! error TS1241: Unable to resolve signature of method decorator when called as an expression. -!!! error TS1241: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty11.errors.txt b/tests/baselines/reference/decoratorOnClassProperty11.errors.txt index 6ff700564e8..2a72fefa53e 100644 --- a/tests/baselines/reference/decoratorOnClassProperty11.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty11.errors.txt @@ -1,5 +1,4 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts(4,5): error TS1240: Unable to resolve signature of property decorator when called as an expression. - Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts (1 errors) ==== @@ -9,5 +8,4 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts( @dec prop; ~~~~ !!! error TS1240: Unable to resolve signature of property decorator when called as an expression. -!!! error TS1240: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty6.errors.txt b/tests/baselines/reference/decoratorOnClassProperty6.errors.txt index dbb104e8cd3..b40a81fe1c9 100644 --- a/tests/baselines/reference/decoratorOnClassProperty6.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty6.errors.txt @@ -1,5 +1,4 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4,5): error TS1240: Unable to resolve signature of property decorator when called as an expression. - Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts (1 errors) ==== @@ -9,5 +8,4 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4 @dec prop; ~~~~ !!! error TS1240: Unable to resolve signature of property decorator when called as an expression. -!!! error TS1240: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty7.errors.txt b/tests/baselines/reference/decoratorOnClassProperty7.errors.txt index 41396acd17e..47f8ad5ae8c 100644 --- a/tests/baselines/reference/decoratorOnClassProperty7.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty7.errors.txt @@ -1,5 +1,4 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4,5): error TS1240: Unable to resolve signature of property decorator when called as an expression. - Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts (1 errors) ==== @@ -9,5 +8,4 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4 @dec prop; ~~~~ !!! error TS1240: Unable to resolve signature of property decorator when called as an expression. -!!! error TS1240: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt b/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt index 75720d86404..b8fa513e289 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts(11,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts(24,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts(11,9): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts(24,9): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts (2 errors) ==== @@ -15,7 +15,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var r = new Derived(); // error ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var r2 = new Derived(1); class Base2 { @@ -30,5 +30,5 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var d = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var d2 = new D(new Date()); // ok \ No newline at end of file diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt b/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt index b699fb7c89e..0bf92d51f93 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts(13,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts(30,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts(13,9): error TS2554: Expected 1-3 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts(30,9): error TS2554: Expected 1-3 arguments, but got 0. ==== tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts (2 errors) ==== @@ -17,7 +17,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var r = new Derived(); // error ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-3 arguments, but got 0. var r2 = new Derived(1); var r3 = new Derived(1, 2); var r4 = new Derived(1, 2, 3); @@ -36,7 +36,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var d = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-3 arguments, but got 0. var d2 = new D(new Date()); // ok var d3 = new D(new Date(), new Date()); var d4 = new D(new Date(), new Date(), new Date()); \ No newline at end of file diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt b/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt index 6b9619cdac6..79b8cd23606 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(21,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(22,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(44,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(45,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(21,9): error TS2554: Expected 2 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(22,10): error TS2554: Expected 2 arguments, but got 1. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(44,9): error TS2554: Expected 2 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(45,10): error TS2554: Expected 2 arguments, but got 1. ==== tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts (4 errors) ==== @@ -27,10 +27,10 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var r = new Derived(); // error ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 0. var r2 = new Derived2(1); // error ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 1. var r3 = new Derived('', ''); class Base2 { @@ -54,8 +54,8 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var d = new D2(); // error ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 0. var d2 = new D2(new Date()); // error ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 1. var d3 = new D2(new Date(), new Date()); // ok \ No newline at end of file diff --git a/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt b/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt index 3410867f818..ba1b05944fd 100644 --- a/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt +++ b/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts(13,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts(13,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts (1 errors) ==== @@ -16,4 +16,4 @@ tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts(13,1): erro var y: MyClass = new MyClass(); y.myMethod(); // error ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/destructureOptionalParameter.types b/tests/baselines/reference/destructureOptionalParameter.types index f007a992c9e..18a6d7675dd 100644 --- a/tests/baselines/reference/destructureOptionalParameter.types +++ b/tests/baselines/reference/destructureOptionalParameter.types @@ -1,13 +1,13 @@ === tests/cases/compiler/destructureOptionalParameter.ts === declare function f1({ a, b }?: { a: number, b: string }): void; ->f1 : ({a, b}?: { a: number; b: string; } | undefined) => void +>f1 : ({ a, b }?: { a: number; b: string; } | undefined) => void >a : number >b : string >a : number >b : string function f2({ a, b }: { a: number, b: number } = { a: 0, b: 0 }) { ->f2 : ({a, b}?: { a: number; b: number; }) => void +>f2 : ({ a, b }?: { a: number; b: number; }) => void >a : number >b : number >a : number diff --git a/tests/baselines/reference/destructuringParameterDeclaration2.errors.txt b/tests/baselines/reference/destructuringParameterDeclaration2.errors.txt index d76a4efe5f1..81c85f7c42b 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration2.errors.txt +++ b/tests/baselines/reference/destructuringParameterDeclaration2.errors.txt @@ -38,7 +38,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts( tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts(47,13): error TS2463: A binding pattern parameter cannot be optional in an implementation signature. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts(55,7): error TS2420: Class 'C4' incorrectly implements interface 'F2'. Types of property 'd4' are incompatible. - Type '({x, y, c}: { x: any; y: any; c: any; }) => void' is not assignable to type '({x, y, z}?: { x: any; y: any; z: any; }) => any'. + Type '({ x, y, c }: { x: any; y: any; c: any; }) => void' is not assignable to type '({ x, y, z }?: { x: any; y: any; z: any; }) => any'. Types of parameters '__0' and '__0' are incompatible. Type '{ x: any; y: any; z: any; }' is not assignable to type '{ x: any; y: any; c: any; }'. Property 'c' is missing in type '{ x: any; y: any; z: any; }'. @@ -162,7 +162,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts( ~~ !!! error TS2420: Class 'C4' incorrectly implements interface 'F2'. !!! error TS2420: Types of property 'd4' are incompatible. -!!! error TS2420: Type '({x, y, c}: { x: any; y: any; c: any; }) => void' is not assignable to type '({x, y, z}?: { x: any; y: any; z: any; }) => any'. +!!! error TS2420: Type '({ x, y, c }: { x: any; y: any; c: any; }) => void' is not assignable to type '({ x, y, z }?: { x: any; y: any; z: any; }) => any'. !!! error TS2420: Types of parameters '__0' and '__0' are incompatible. !!! error TS2420: Type '{ x: any; y: any; z: any; }' is not assignable to type '{ x: any; y: any; c: any; }'. !!! error TS2420: Property 'c' is missing in type '{ x: any; y: any; z: any; }'. diff --git a/tests/baselines/reference/destructuringParameterDeclaration4.errors.txt b/tests/baselines/reference/destructuringParameterDeclaration4.errors.txt index 8db71591f47..cdc7938d1af 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration4.errors.txt +++ b/tests/baselines/reference/destructuringParameterDeclaration4.errors.txt @@ -3,7 +3,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts( tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(14,17): error TS1047: A rest parameter cannot be optional. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(15,16): error TS1048: A rest parameter cannot have an initializer. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(20,19): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. -tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(21,7): error TS2304: Cannot find name 'array2'. +tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(21,7): error TS2552: Cannot find name 'array2'. Did you mean 'Array'? tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(22,4): error TS2345: Argument of type '[number, number, string, boolean, boolean]' is not assignable to parameter of type '[any, any, [[any]]]'. Types of property '2' are incompatible. Type 'string' is not assignable to type '[[any]]'. @@ -50,7 +50,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts( !!! error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. a1(...array2); // Error parameter type is (number|string)[] ~~~~~~ -!!! error TS2304: Cannot find name 'array2'. +!!! error TS2552: Cannot find name 'array2'. Did you mean 'Array'? a5([1, 2, "string", false, true]); // Error, parameter type is [any, any, [[any]]] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '[number, number, string, boolean, boolean]' is not assignable to parameter of type '[any, any, [[any]]]'. diff --git a/tests/baselines/reference/destructuringParameterDeclaration7ES5.types b/tests/baselines/reference/destructuringParameterDeclaration7ES5.types index 502a176596a..40a07f02276 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration7ES5.types +++ b/tests/baselines/reference/destructuringParameterDeclaration7ES5.types @@ -10,13 +10,13 @@ interface ISomething { } function foo({}, {foo, bar}: ISomething) {} ->foo : ({}: {}, {foo, bar}: ISomething) => void +>foo : ({}: {}, { foo, bar }: ISomething) => void >foo : string >bar : string >ISomething : ISomething function baz([], {foo, bar}: ISomething) {} ->baz : ([]: any[], {foo, bar}: ISomething) => void +>baz : ([]: any[], { foo, bar }: ISomething) => void >foo : string >bar : string >ISomething : ISomething diff --git a/tests/baselines/reference/destructuringParameterDeclaration7ES5iterable.types b/tests/baselines/reference/destructuringParameterDeclaration7ES5iterable.types index 542407cabe2..607c34cdd37 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration7ES5iterable.types +++ b/tests/baselines/reference/destructuringParameterDeclaration7ES5iterable.types @@ -10,13 +10,13 @@ interface ISomething { } function foo({}, {foo, bar}: ISomething) {} ->foo : ({}: {}, {foo, bar}: ISomething) => void +>foo : ({}: {}, { foo, bar }: ISomething) => void >foo : string >bar : string >ISomething : ISomething function baz([], {foo, bar}: ISomething) {} ->baz : ([]: any[], {foo, bar}: ISomething) => void +>baz : ([]: any[], { foo, bar }: ISomething) => void >foo : string >bar : string >ISomething : ISomething diff --git a/tests/baselines/reference/destructuringWithGenericParameter.types b/tests/baselines/reference/destructuringWithGenericParameter.types index 07a86e679a9..430d6e0faca 100644 --- a/tests/baselines/reference/destructuringWithGenericParameter.types +++ b/tests/baselines/reference/destructuringWithGenericParameter.types @@ -36,7 +36,7 @@ genericFunction(genericObject, ({greeting}) => { >genericFunction(genericObject, ({greeting}) => { var s = greeting.toLocaleLowerCase(); // Greeting should be of type string}) : void >genericFunction : (object: GenericClass, callback: (payload: T) => void) => void >genericObject : GenericClass<{ greeting: string; }> ->({greeting}) => { var s = greeting.toLocaleLowerCase(); // Greeting should be of type string} : ({greeting}: { greeting: string; }) => void +>({greeting}) => { var s = greeting.toLocaleLowerCase(); // Greeting should be of type string} : ({ greeting }: { greeting: string; }) => void >greeting : string var s = greeting.toLocaleLowerCase(); // Greeting should be of type string diff --git a/tests/baselines/reference/destructuringWithLiteralInitializers.types b/tests/baselines/reference/destructuringWithLiteralInitializers.types index 43391515014..51c432f7605 100644 --- a/tests/baselines/reference/destructuringWithLiteralInitializers.types +++ b/tests/baselines/reference/destructuringWithLiteralInitializers.types @@ -1,13 +1,13 @@ === tests/cases/conformance/es6/destructuring/destructuringWithLiteralInitializers.ts === // (arg: { x: any, y: any }) => void function f1({ x, y }) { } ->f1 : ({x, y}: { x: any; y: any; }) => void +>f1 : ({ x, y }: { x: any; y: any; }) => void >x : any >y : any f1({ x: 1, y: 1 }); >f1({ x: 1, y: 1 }) : void ->f1 : ({x, y}: { x: any; y: any; }) => void +>f1 : ({ x, y }: { x: any; y: any; }) => void >{ x: 1, y: 1 } : { x: number; y: number; } >x : number >1 : 1 @@ -16,21 +16,21 @@ f1({ x: 1, y: 1 }); // (arg: { x: any, y?: number }) => void function f2({ x, y = 0 }) { } ->f2 : ({x, y}: { x: any; y?: number; }) => void +>f2 : ({ x, y }: { x: any; y?: number; }) => void >x : any >y : number >0 : 0 f2({ x: 1 }); >f2({ x: 1 }) : void ->f2 : ({x, y}: { x: any; y?: number; }) => void +>f2 : ({ x, y }: { x: any; y?: number; }) => void >{ x: 1 } : { x: number; } >x : number >1 : 1 f2({ x: 1, y: 1 }); >f2({ x: 1, y: 1 }) : void ->f2 : ({x, y}: { x: any; y?: number; }) => void +>f2 : ({ x, y }: { x: any; y?: number; }) => void >{ x: 1, y: 1 } : { x: number; y: number; } >x : number >1 : 1 @@ -39,7 +39,7 @@ f2({ x: 1, y: 1 }); // (arg: { x?: number, y?: number }) => void function f3({ x = 0, y = 0 }) { } ->f3 : ({x, y}: { x?: number; y?: number; }) => void +>f3 : ({ x, y }: { x?: number; y?: number; }) => void >x : number >0 : 0 >y : number @@ -47,26 +47,26 @@ function f3({ x = 0, y = 0 }) { } f3({}); >f3({}) : void ->f3 : ({x, y}: { x?: number; y?: number; }) => void +>f3 : ({ x, y }: { x?: number; y?: number; }) => void >{} : {} f3({ x: 1 }); >f3({ x: 1 }) : void ->f3 : ({x, y}: { x?: number; y?: number; }) => void +>f3 : ({ x, y }: { x?: number; y?: number; }) => void >{ x: 1 } : { x: number; } >x : number >1 : 1 f3({ y: 1 }); >f3({ y: 1 }) : void ->f3 : ({x, y}: { x?: number; y?: number; }) => void +>f3 : ({ x, y }: { x?: number; y?: number; }) => void >{ y: 1 } : { y: number; } >y : number >1 : 1 f3({ x: 1, y: 1 }); >f3({ x: 1, y: 1 }) : void ->f3 : ({x, y}: { x?: number; y?: number; }) => void +>f3 : ({ x, y }: { x?: number; y?: number; }) => void >{ x: 1, y: 1 } : { x: number; y: number; } >x : number >1 : 1 @@ -75,7 +75,7 @@ f3({ x: 1, y: 1 }); // (arg?: { x: number, y: number }) => void function f4({ x, y } = { x: 0, y: 0 }) { } ->f4 : ({x, y}?: { x: number; y: number; }) => void +>f4 : ({ x, y }?: { x: number; y: number; }) => void >x : number >y : number >{ x: 0, y: 0 } : { x: number; y: number; } @@ -86,11 +86,11 @@ function f4({ x, y } = { x: 0, y: 0 }) { } f4(); >f4() : void ->f4 : ({x, y}?: { x: number; y: number; }) => void +>f4 : ({ x, y }?: { x: number; y: number; }) => void f4({ x: 1, y: 1 }); >f4({ x: 1, y: 1 }) : void ->f4 : ({x, y}?: { x: number; y: number; }) => void +>f4 : ({ x, y }?: { x: number; y: number; }) => void >{ x: 1, y: 1 } : { x: number; y: number; } >x : number >1 : 1 @@ -99,7 +99,7 @@ f4({ x: 1, y: 1 }); // (arg?: { x: number, y?: number }) => void function f5({ x, y = 0 } = { x: 0 }) { } ->f5 : ({x, y}?: { x: number; y?: number; }) => void +>f5 : ({ x, y }?: { x: number; y?: number; }) => void >x : number >y : number >0 : 0 @@ -109,18 +109,18 @@ function f5({ x, y = 0 } = { x: 0 }) { } f5(); >f5() : void ->f5 : ({x, y}?: { x: number; y?: number; }) => void +>f5 : ({ x, y }?: { x: number; y?: number; }) => void f5({ x: 1 }); >f5({ x: 1 }) : void ->f5 : ({x, y}?: { x: number; y?: number; }) => void +>f5 : ({ x, y }?: { x: number; y?: number; }) => void >{ x: 1 } : { x: number; } >x : number >1 : 1 f5({ x: 1, y: 1 }); >f5({ x: 1, y: 1 }) : void ->f5 : ({x, y}?: { x: number; y?: number; }) => void +>f5 : ({ x, y }?: { x: number; y?: number; }) => void >{ x: 1, y: 1 } : { x: number; y: number; } >x : number >1 : 1 @@ -129,7 +129,7 @@ f5({ x: 1, y: 1 }); // (arg?: { x?: number, y?: number }) => void function f6({ x = 0, y = 0 } = {}) { } ->f6 : ({x, y}?: { x?: number; y?: number; }) => void +>f6 : ({ x, y }?: { x?: number; y?: number; }) => void >x : number >0 : 0 >y : number @@ -138,30 +138,30 @@ function f6({ x = 0, y = 0 } = {}) { } f6(); >f6() : void ->f6 : ({x, y}?: { x?: number; y?: number; }) => void +>f6 : ({ x, y }?: { x?: number; y?: number; }) => void f6({}); >f6({}) : void ->f6 : ({x, y}?: { x?: number; y?: number; }) => void +>f6 : ({ x, y }?: { x?: number; y?: number; }) => void >{} : {} f6({ x: 1 }); >f6({ x: 1 }) : void ->f6 : ({x, y}?: { x?: number; y?: number; }) => void +>f6 : ({ x, y }?: { x?: number; y?: number; }) => void >{ x: 1 } : { x: number; } >x : number >1 : 1 f6({ y: 1 }); >f6({ y: 1 }) : void ->f6 : ({x, y}?: { x?: number; y?: number; }) => void +>f6 : ({ x, y }?: { x?: number; y?: number; }) => void >{ y: 1 } : { y: number; } >y : number >1 : 1 f6({ x: 1, y: 1 }); >f6({ x: 1, y: 1 }) : void ->f6 : ({x, y}?: { x?: number; y?: number; }) => void +>f6 : ({ x, y }?: { x?: number; y?: number; }) => void >{ x: 1, y: 1 } : { x: number; y: number; } >x : number >1 : 1 @@ -170,7 +170,7 @@ f6({ x: 1, y: 1 }); // (arg?: { a: { x?: number, y?: number } }) => void function f7({ a: { x = 0, y = 0 } } = { a: {} }) { } ->f7 : ({a: {x, y}}?: { a: { x?: number; y?: number; }; }) => void +>f7 : ({ a: { x, y } }?: { a: { x?: number; y?: number; }; }) => void >a : any >x : number >0 : 0 @@ -182,18 +182,18 @@ function f7({ a: { x = 0, y = 0 } } = { a: {} }) { } f7(); >f7() : void ->f7 : ({a: {x, y}}?: { a: { x?: number; y?: number; }; }) => void +>f7 : ({ a: { x, y } }?: { a: { x?: number; y?: number; }; }) => void f7({ a: {} }); >f7({ a: {} }) : void ->f7 : ({a: {x, y}}?: { a: { x?: number; y?: number; }; }) => void +>f7 : ({ a: { x, y } }?: { a: { x?: number; y?: number; }; }) => void >{ a: {} } : { a: {}; } >a : {} >{} : {} f7({ a: { x: 1 } }); >f7({ a: { x: 1 } }) : void ->f7 : ({a: {x, y}}?: { a: { x?: number; y?: number; }; }) => void +>f7 : ({ a: { x, y } }?: { a: { x?: number; y?: number; }; }) => void >{ a: { x: 1 } } : { a: { x: number; }; } >a : { x: number; } >{ x: 1 } : { x: number; } @@ -202,7 +202,7 @@ f7({ a: { x: 1 } }); f7({ a: { y: 1 } }); >f7({ a: { y: 1 } }) : void ->f7 : ({a: {x, y}}?: { a: { x?: number; y?: number; }; }) => void +>f7 : ({ a: { x, y } }?: { a: { x?: number; y?: number; }; }) => void >{ a: { y: 1 } } : { a: { y: number; }; } >a : { y: number; } >{ y: 1 } : { y: number; } @@ -211,7 +211,7 @@ f7({ a: { y: 1 } }); f7({ a: { x: 1, y: 1 } }); >f7({ a: { x: 1, y: 1 } }) : void ->f7 : ({a: {x, y}}?: { a: { x?: number; y?: number; }; }) => void +>f7 : ({ a: { x, y } }?: { a: { x?: number; y?: number; }; }) => void >{ a: { x: 1, y: 1 } } : { a: { x: number; y: number; }; } >a : { x: number; y: number; } >{ x: 1, y: 1 } : { x: number; y: number; } diff --git a/tests/baselines/reference/dottedModuleName.errors.txt b/tests/baselines/reference/dottedModuleName.errors.txt index afb8b944355..a2fa71430f8 100644 --- a/tests/baselines/reference/dottedModuleName.errors.txt +++ b/tests/baselines/reference/dottedModuleName.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/dottedModuleName.ts(3,29): error TS1144: '{' or ';' expected. -tests/cases/compiler/dottedModuleName.ts(3,33): error TS2304: Cannot find name 'x'. +tests/cases/compiler/dottedModuleName.ts(3,33): error TS2552: Cannot find name 'x'. Did you mean 'X'? ==== tests/cases/compiler/dottedModuleName.ts (2 errors) ==== @@ -9,7 +9,7 @@ tests/cases/compiler/dottedModuleName.ts(3,33): error TS2304: Cannot find name ' ~~ !!! error TS1144: '{' or ';' expected. ~ -!!! error TS2304: Cannot find name 'x'. +!!! error TS2552: Cannot find name 'x'. Did you mean 'X'? export module X.Y.Z { export var v2=f(v); } diff --git a/tests/baselines/reference/emitArrowFunctionES6.types b/tests/baselines/reference/emitArrowFunctionES6.types index c434e4b285a..314d5e464b7 100644 --- a/tests/baselines/reference/emitArrowFunctionES6.types +++ b/tests/baselines/reference/emitArrowFunctionES6.types @@ -70,25 +70,25 @@ var p5 = ([a = 1]) => { }; >1 : 1 var p6 = ({ a }) => { }; ->p6 : ({a}: { a: any; }) => void ->({ a }) => { } : ({a}: { a: any; }) => void +>p6 : ({ a }: { a: any; }) => void +>({ a }) => { } : ({ a }: { a: any; }) => void >a : any var p7 = ({ a: { b } }) => { }; ->p7 : ({a: {b}}: { a: { b: any; }; }) => void ->({ a: { b } }) => { } : ({a: {b}}: { a: { b: any; }; }) => void +>p7 : ({ a: { b } }: { a: { b: any; }; }) => void +>({ a: { b } }) => { } : ({ a: { b } }: { a: { b: any; }; }) => void >a : any >b : any var p8 = ({ a = 1 }) => { }; ->p8 : ({a}: { a?: number; }) => void ->({ a = 1 }) => { } : ({a}: { a?: number; }) => void +>p8 : ({ a }: { a?: number; }) => void +>({ a = 1 }) => { } : ({ a }: { a?: number; }) => void >a : number >1 : 1 var p9 = ({ a: { b = 1 } = { b: 1 } }) => { }; ->p9 : ({a: {b}}: { a?: { b?: number; }; }) => void ->({ a: { b = 1 } = { b: 1 } }) => { } : ({a: {b}}: { a?: { b?: number; }; }) => void +>p9 : ({ a: { b } }: { a?: { b?: number; }; }) => void +>({ a: { b = 1 } = { b: 1 } }) => { } : ({ a: { b } }: { a?: { b?: number; }; }) => void >a : any >b : number >1 : 1 @@ -97,8 +97,8 @@ var p9 = ({ a: { b = 1 } = { b: 1 } }) => { }; >1 : 1 var p10 = ([{ value, done }]) => { }; ->p10 : ([{value, done}]: [{ value: any; done: any; }]) => void ->([{ value, done }]) => { } : ([{value, done}]: [{ value: any; done: any; }]) => void +>p10 : ([{ value, done }]: [{ value: any; done: any; }]) => void +>([{ value, done }]) => { } : ([{ value, done }]: [{ value: any; done: any; }]) => void >value : any >done : any diff --git a/tests/baselines/reference/emitClassExpressionInDeclarationFile.js b/tests/baselines/reference/emitClassExpressionInDeclarationFile.js new file mode 100644 index 00000000000..ab64fe003be --- /dev/null +++ b/tests/baselines/reference/emitClassExpressionInDeclarationFile.js @@ -0,0 +1,132 @@ +//// [emitClassExpressionInDeclarationFile.ts] +export var simpleExample = class { + static getTags() { } + tags() { } +} +export var circularReference = class C { + static getTags(c: C): C { return c } + tags(c: C): C { return c } +} + +// repro from #15066 +export class FooItem { + foo(): void { } + name?: string; +} + +export type Constructor = new(...args: any[]) => T; +export function WithTags>(Base: T) { + return class extends Base { + static getTags(): void { } + tags(): void { } + } +} + +export class Test extends WithTags(FooItem) {} + +const test = new Test(); + +Test.getTags() +test.tags(); + + +//// [emitClassExpressionInDeclarationFile.js] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +exports.simpleExample = (function () { + function class_1() { + } + class_1.getTags = function () { }; + class_1.prototype.tags = function () { }; + return class_1; +}()); +exports.circularReference = (function () { + function C() { + } + C.getTags = function (c) { return c; }; + C.prototype.tags = function (c) { return c; }; + return C; +}()); +// repro from #15066 +var FooItem = (function () { + function FooItem() { + } + FooItem.prototype.foo = function () { }; + return FooItem; +}()); +exports.FooItem = FooItem; +function WithTags(Base) { + return (function (_super) { + __extends(class_2, _super); + function class_2() { + return _super !== null && _super.apply(this, arguments) || this; + } + class_2.getTags = function () { }; + class_2.prototype.tags = function () { }; + return class_2; + }(Base)); +} +exports.WithTags = WithTags; +var Test = (function (_super) { + __extends(Test, _super); + function Test() { + return _super !== null && _super.apply(this, arguments) || this; + } + return Test; +}(WithTags(FooItem))); +exports.Test = Test; +var test = new Test(); +Test.getTags(); +test.tags(); + + +//// [emitClassExpressionInDeclarationFile.d.ts] +export declare var simpleExample: { + new (): { + tags(): void; + }; + getTags(): void; +}; +export declare var circularReference: { + new (): { + tags(c: any): any; + }; + getTags(c: { + tags(c: any): any; + }): { + tags(c: any): any; + }; +}; +export declare class FooItem { + foo(): void; + name?: string; +} +export declare type Constructor = new (...args: any[]) => T; +export declare function WithTags>(Base: T): { + new (...args: any[]): { + tags(): void; + foo(): void; + name?: string; + }; + getTags(): void; +} & T; +declare const Test_base: { + new (...args: any[]): { + tags(): void; + foo(): void; + name?: string; + }; + getTags(): void; +} & typeof FooItem; +export declare class Test extends Test_base { +} diff --git a/tests/baselines/reference/emitClassExpressionInDeclarationFile.symbols b/tests/baselines/reference/emitClassExpressionInDeclarationFile.symbols new file mode 100644 index 00000000000..537838937c5 --- /dev/null +++ b/tests/baselines/reference/emitClassExpressionInDeclarationFile.symbols @@ -0,0 +1,84 @@ +=== tests/cases/compiler/emitClassExpressionInDeclarationFile.ts === +export var simpleExample = class { +>simpleExample : Symbol(simpleExample, Decl(emitClassExpressionInDeclarationFile.ts, 0, 10)) + + static getTags() { } +>getTags : Symbol(simpleExample.getTags, Decl(emitClassExpressionInDeclarationFile.ts, 0, 34)) + + tags() { } +>tags : Symbol(simpleExample.tags, Decl(emitClassExpressionInDeclarationFile.ts, 1, 24)) +} +export var circularReference = class C { +>circularReference : Symbol(circularReference, Decl(emitClassExpressionInDeclarationFile.ts, 4, 10)) +>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30)) + + static getTags(c: C): C { return c } +>getTags : Symbol(C.getTags, Decl(emitClassExpressionInDeclarationFile.ts, 4, 40)) +>c : Symbol(c, Decl(emitClassExpressionInDeclarationFile.ts, 5, 19)) +>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30)) +>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30)) +>c : Symbol(c, Decl(emitClassExpressionInDeclarationFile.ts, 5, 19)) + + tags(c: C): C { return c } +>tags : Symbol(C.tags, Decl(emitClassExpressionInDeclarationFile.ts, 5, 40)) +>c : Symbol(c, Decl(emitClassExpressionInDeclarationFile.ts, 6, 9)) +>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30)) +>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30)) +>c : Symbol(c, Decl(emitClassExpressionInDeclarationFile.ts, 6, 9)) +} + +// repro from #15066 +export class FooItem { +>FooItem : Symbol(FooItem, Decl(emitClassExpressionInDeclarationFile.ts, 7, 1)) + + foo(): void { } +>foo : Symbol(FooItem.foo, Decl(emitClassExpressionInDeclarationFile.ts, 10, 22)) + + name?: string; +>name : Symbol(FooItem.name, Decl(emitClassExpressionInDeclarationFile.ts, 11, 19)) +} + +export type Constructor = new(...args: any[]) => T; +>Constructor : Symbol(Constructor, Decl(emitClassExpressionInDeclarationFile.ts, 13, 1)) +>T : Symbol(T, Decl(emitClassExpressionInDeclarationFile.ts, 15, 24)) +>args : Symbol(args, Decl(emitClassExpressionInDeclarationFile.ts, 15, 33)) +>T : Symbol(T, Decl(emitClassExpressionInDeclarationFile.ts, 15, 24)) + +export function WithTags>(Base: T) { +>WithTags : Symbol(WithTags, Decl(emitClassExpressionInDeclarationFile.ts, 15, 54)) +>T : Symbol(T, Decl(emitClassExpressionInDeclarationFile.ts, 16, 25)) +>Constructor : Symbol(Constructor, Decl(emitClassExpressionInDeclarationFile.ts, 13, 1)) +>FooItem : Symbol(FooItem, Decl(emitClassExpressionInDeclarationFile.ts, 7, 1)) +>Base : Symbol(Base, Decl(emitClassExpressionInDeclarationFile.ts, 16, 57)) +>T : Symbol(T, Decl(emitClassExpressionInDeclarationFile.ts, 16, 25)) + + return class extends Base { +>Base : Symbol(Base, Decl(emitClassExpressionInDeclarationFile.ts, 16, 57)) + + static getTags(): void { } +>getTags : Symbol((Anonymous class).getTags, Decl(emitClassExpressionInDeclarationFile.ts, 17, 31)) + + tags(): void { } +>tags : Symbol((Anonymous class).tags, Decl(emitClassExpressionInDeclarationFile.ts, 18, 34)) + } +} + +export class Test extends WithTags(FooItem) {} +>Test : Symbol(Test, Decl(emitClassExpressionInDeclarationFile.ts, 21, 1)) +>WithTags : Symbol(WithTags, Decl(emitClassExpressionInDeclarationFile.ts, 15, 54)) +>FooItem : Symbol(FooItem, Decl(emitClassExpressionInDeclarationFile.ts, 7, 1)) + +const test = new Test(); +>test : Symbol(test, Decl(emitClassExpressionInDeclarationFile.ts, 25, 5)) +>Test : Symbol(Test, Decl(emitClassExpressionInDeclarationFile.ts, 21, 1)) + +Test.getTags() +>Test.getTags : Symbol((Anonymous class).getTags, Decl(emitClassExpressionInDeclarationFile.ts, 17, 31)) +>Test : Symbol(Test, Decl(emitClassExpressionInDeclarationFile.ts, 21, 1)) +>getTags : Symbol((Anonymous class).getTags, Decl(emitClassExpressionInDeclarationFile.ts, 17, 31)) + +test.tags(); +>test.tags : Symbol((Anonymous class).tags, Decl(emitClassExpressionInDeclarationFile.ts, 18, 34)) +>test : Symbol(test, Decl(emitClassExpressionInDeclarationFile.ts, 25, 5)) +>tags : Symbol((Anonymous class).tags, Decl(emitClassExpressionInDeclarationFile.ts, 18, 34)) + diff --git a/tests/baselines/reference/emitClassExpressionInDeclarationFile.types b/tests/baselines/reference/emitClassExpressionInDeclarationFile.types new file mode 100644 index 00000000000..3d5190262de --- /dev/null +++ b/tests/baselines/reference/emitClassExpressionInDeclarationFile.types @@ -0,0 +1,91 @@ +=== tests/cases/compiler/emitClassExpressionInDeclarationFile.ts === +export var simpleExample = class { +>simpleExample : typeof simpleExample +>class { static getTags() { } tags() { }} : typeof simpleExample + + static getTags() { } +>getTags : () => void + + tags() { } +>tags : () => void +} +export var circularReference = class C { +>circularReference : typeof C +>class C { static getTags(c: C): C { return c } tags(c: C): C { return c }} : typeof C +>C : typeof C + + static getTags(c: C): C { return c } +>getTags : (c: C) => C +>c : C +>C : C +>C : C +>c : C + + tags(c: C): C { return c } +>tags : (c: C) => C +>c : C +>C : C +>C : C +>c : C +} + +// repro from #15066 +export class FooItem { +>FooItem : FooItem + + foo(): void { } +>foo : () => void + + name?: string; +>name : string +} + +export type Constructor = new(...args: any[]) => T; +>Constructor : Constructor +>T : T +>args : any[] +>T : T + +export function WithTags>(Base: T) { +>WithTags : >(Base: T) => { new (...args: any[]): (Anonymous class); prototype: WithTags.(Anonymous class); getTags(): void; } & T +>T : T +>Constructor : Constructor +>FooItem : FooItem +>Base : T +>T : T + + return class extends Base { +>class extends Base { static getTags(): void { } tags(): void { } } : { new (...args: any[]): (Anonymous class); prototype: WithTags.(Anonymous class); getTags(): void; } & T +>Base : FooItem + + static getTags(): void { } +>getTags : () => void + + tags(): void { } +>tags : () => void + } +} + +export class Test extends WithTags(FooItem) {} +>Test : Test +>WithTags(FooItem) : WithTags.(Anonymous class) & FooItem +>WithTags : >(Base: T) => { new (...args: any[]): (Anonymous class); prototype: WithTags.(Anonymous class); getTags(): void; } & T +>FooItem : typeof FooItem + +const test = new Test(); +>test : Test +>new Test() : Test +>Test : typeof Test + +Test.getTags() +>Test.getTags() : void +>Test.getTags : () => void +>Test : typeof Test +>getTags : () => void + +test.tags(); +>test.tags() : void +>test.tags : () => void +>test : Test +>tags : () => void + diff --git a/tests/baselines/reference/emitClassExpressionInDeclarationFile2.errors.txt b/tests/baselines/reference/emitClassExpressionInDeclarationFile2.errors.txt new file mode 100644 index 00000000000..4541cf2a58a --- /dev/null +++ b/tests/baselines/reference/emitClassExpressionInDeclarationFile2.errors.txt @@ -0,0 +1,41 @@ +tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts(1,12): error TS4094: Property 'p' of exported class expression may not be private or protected. +tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts(1,12): error TS4094: Property 'ps' of exported class expression may not be private or protected. +tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts(16,17): error TS4094: Property 'property' of exported class expression may not be private or protected. + + +==== tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts (3 errors) ==== + export var noPrivates = class { + ~~~~~~~~~~ +!!! error TS4094: Property 'p' of exported class expression may not be private or protected. + ~~~~~~~~~~ +!!! error TS4094: Property 'ps' of exported class expression may not be private or protected. + static getTags() { } + tags() { } + private static ps = -1 + private p = 12 + } + + // altered repro from #15066 to add private property + export class FooItem { + foo(): void { } + name?: string; + private property = "capitalism" + } + + export type Constructor = new(...args: any[]) => T; + export function WithTags>(Base: T) { + ~~~~~~~~ +!!! error TS4094: Property 'property' of exported class expression may not be private or protected. + return class extends Base { + static getTags(): void { } + tags(): void { } + } + } + + export class Test extends WithTags(FooItem) {} + + const test = new Test(); + + Test.getTags() + test.tags(); + \ No newline at end of file diff --git a/tests/baselines/reference/emitClassExpressionInDeclarationFile2.js b/tests/baselines/reference/emitClassExpressionInDeclarationFile2.js new file mode 100644 index 00000000000..e3a0aa4cb99 --- /dev/null +++ b/tests/baselines/reference/emitClassExpressionInDeclarationFile2.js @@ -0,0 +1,87 @@ +//// [emitClassExpressionInDeclarationFile2.ts] +export var noPrivates = class { + static getTags() { } + tags() { } + private static ps = -1 + private p = 12 +} + +// altered repro from #15066 to add private property +export class FooItem { + foo(): void { } + name?: string; + private property = "capitalism" +} + +export type Constructor = new(...args: any[]) => T; +export function WithTags>(Base: T) { + return class extends Base { + static getTags(): void { } + tags(): void { } + } +} + +export class Test extends WithTags(FooItem) {} + +const test = new Test(); + +Test.getTags() +test.tags(); + + +//// [emitClassExpressionInDeclarationFile2.js] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +exports.noPrivates = (_a = (function () { + function class_1() { + this.p = 12; + } + class_1.getTags = function () { }; + class_1.prototype.tags = function () { }; + return class_1; + }()), + _a.ps = -1, + _a); +// altered repro from #15066 to add private property +var FooItem = (function () { + function FooItem() { + this.property = "capitalism"; + } + FooItem.prototype.foo = function () { }; + return FooItem; +}()); +exports.FooItem = FooItem; +function WithTags(Base) { + return (function (_super) { + __extends(class_2, _super); + function class_2() { + return _super !== null && _super.apply(this, arguments) || this; + } + class_2.getTags = function () { }; + class_2.prototype.tags = function () { }; + return class_2; + }(Base)); +} +exports.WithTags = WithTags; +var Test = (function (_super) { + __extends(Test, _super); + function Test() { + return _super !== null && _super.apply(this, arguments) || this; + } + return Test; +}(WithTags(FooItem))); +exports.Test = Test; +var test = new Test(); +Test.getTags(); +test.tags(); +var _a; diff --git a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js index fbefef62d05..d91571f93ad 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js @@ -61,18 +61,17 @@ class C9 extends B9 { //// [C1.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C1 { f() { @@ -81,143 +80,137 @@ class C1 { } } //// [C2.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C2 { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["yield"]; + const x = yield; }); } } //// [C3.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C3 { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["yield", 1]; + const x = yield 1; }); } } //// [C4.js] -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C4 { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield* __asyncDelegator([1]); + const x = yield __await(yield* __asyncDelegator(__asyncValues([1]))); }); } } //// [C5.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; class C5 { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })()); + const x = yield __await(yield* __asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function* () { yield 1; }); })()))); }); } } //// [C6.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C6 { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["await", 1]; + const x = yield __await(1); }); } } //// [C7.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C7 { f() { @@ -227,18 +220,17 @@ class C7 { } } //// [C8.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C8 { g() { @@ -250,18 +242,17 @@ class C8 { } } //// [C9.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class B9 { g() { } diff --git a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js index 0c58c4735a0..cfd7c9725e4 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js @@ -88,18 +88,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var C1 = (function () { function C1() { @@ -141,18 +140,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var C2 = (function () { function C2() { @@ -162,7 +160,7 @@ var C2 = (function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield"]]; + case 0: return [4 /*yield*/]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -200,18 +198,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var C3 = (function () { function C3() { @@ -221,7 +218,7 @@ var C3 = (function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -259,28 +256,27 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; @@ -300,8 +296,9 @@ var C4 = (function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator([1]))]; - case 1: + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: x = _a.sent(); return [2 /*return*/]; } @@ -338,29 +335,28 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); @@ -379,15 +375,16 @@ var C5 = (function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: _a.sent(); return [2 /*return*/]; } - }); }); })()))]; - case 1: + }); }); })())))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: x = _a.sent(); return [2 /*return*/]; } @@ -424,18 +421,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var C6 = (function () { function C6() { @@ -445,7 +441,7 @@ var C6 = (function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["await", 1]]; + case 0: return [4 /*yield*/, __await(1)]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -483,18 +479,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var C7 = (function () { function C7() { @@ -536,18 +531,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var C8 = (function () { function C8() { @@ -602,18 +596,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var B9 = (function () { function B9() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js index daf188ba33f..4ca8322da9f 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js @@ -30,151 +30,144 @@ async function * f7() { //// [F1.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f1() { return __asyncGenerator(this, arguments, function* f1_1() { }); } //// [F2.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f2() { return __asyncGenerator(this, arguments, function* f2_1() { - const x = yield ["yield"]; + const x = yield; }); } //// [F3.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f3() { return __asyncGenerator(this, arguments, function* f3_1() { - const x = yield ["yield", 1]; + const x = yield 1; }); } //// [F4.js] -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f4() { return __asyncGenerator(this, arguments, function* f4_1() { - const x = yield* __asyncDelegator([1]); + const x = yield __await(yield* __asyncDelegator(__asyncValues([1]))); }); } //// [F5.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; function f5() { return __asyncGenerator(this, arguments, function* f5_1() { - const x = yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })()); + const x = yield __await(yield* __asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function* () { yield 1; }); })()))); }); } //// [F6.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f6() { return __asyncGenerator(this, arguments, function* f6_1() { - const x = yield ["await", 1]; + const x = yield __await(1); }); } //// [F7.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f7() { return __asyncGenerator(this, arguments, function* f7_1() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js index 71f685e24dd..410a25d2e16 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js @@ -57,18 +57,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f1() { return __asyncGenerator(this, arguments, function f1_1() { @@ -105,25 +104,24 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f2() { return __asyncGenerator(this, arguments, function f2_1() { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield"]]; + case 0: return [4 /*yield*/]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -159,25 +157,24 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f3() { return __asyncGenerator(this, arguments, function f3_1() { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -213,28 +210,27 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; @@ -251,8 +247,9 @@ function f4() { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator([1]))]; - case 1: + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: x = _a.sent(); return [2 /*return*/]; } @@ -287,29 +284,28 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); @@ -325,15 +321,16 @@ function f5() { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: _a.sent(); return [2 /*return*/]; } - }); }); })()))]; - case 1: + }); }); })())))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: x = _a.sent(); return [2 /*return*/]; } @@ -368,25 +365,24 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f6() { return __asyncGenerator(this, arguments, function f6_1() { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["await", 1]]; + case 0: return [4 /*yield*/, __await(1)]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -422,18 +418,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f7() { return __asyncGenerator(this, arguments, function f7_1() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js index bb2562db780..602fd47d38b 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js @@ -30,151 +30,144 @@ const f7 = async function * () { //// [F1.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const f1 = function () { return __asyncGenerator(this, arguments, function* () { }); }; //// [F2.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const f2 = function () { return __asyncGenerator(this, arguments, function* () { - const x = yield ["yield"]; + const x = yield; }); }; //// [F3.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const f3 = function () { return __asyncGenerator(this, arguments, function* () { - const x = yield ["yield", 1]; + const x = yield 1; }); }; //// [F4.js] -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const f4 = function () { return __asyncGenerator(this, arguments, function* () { - const x = yield* __asyncDelegator([1]); + const x = yield __await(yield* __asyncDelegator(__asyncValues([1]))); }); }; //// [F5.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; const f5 = function () { return __asyncGenerator(this, arguments, function* () { - const x = yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })()); + const x = yield __await(yield* __asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function* () { yield 1; }); })()))); }); }; //// [F6.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const f6 = function () { return __asyncGenerator(this, arguments, function* () { - const x = yield ["await", 1]; + const x = yield __await(1); }); }; //// [F7.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const f7 = function () { return __asyncGenerator(this, arguments, function* () { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js index 1863548c141..45d17737cef 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js @@ -57,18 +57,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var f1 = function () { return __asyncGenerator(this, arguments, function () { @@ -105,25 +104,24 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var f2 = function () { return __asyncGenerator(this, arguments, function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield"]]; + case 0: return [4 /*yield*/]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -159,25 +157,24 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var f3 = function () { return __asyncGenerator(this, arguments, function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -213,28 +210,27 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; @@ -251,8 +247,9 @@ var f4 = function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator([1]))]; - case 1: + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: x = _a.sent(); return [2 /*return*/]; } @@ -287,29 +284,28 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); @@ -325,15 +321,16 @@ var f5 = function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: _a.sent(); return [2 /*return*/]; } - }); }); })()))]; - case 1: + }); }); })())))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: x = _a.sent(); return [2 /*return*/]; } @@ -368,25 +365,24 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var f6 = function () { return __asyncGenerator(this, arguments, function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["await", 1]]; + case 0: return [4 /*yield*/, __await(1)]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -422,18 +418,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var f7 = function () { return __asyncGenerator(this, arguments, function () { diff --git a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js index 5a200349c02..760931a4342 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js @@ -44,18 +44,17 @@ const o7 = { //// [O1.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const o1 = { f() { @@ -64,143 +63,137 @@ const o1 = { } }; //// [O2.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const o2 = { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["yield"]; + const x = yield; }); } }; //// [O3.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const o3 = { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["yield", 1]; + const x = yield 1; }); } }; //// [O4.js] -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const o4 = { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield* __asyncDelegator([1]); + const x = yield __await(yield* __asyncDelegator(__asyncValues([1]))); }); } }; //// [O5.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; const o5 = { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })()); + const x = yield __await(yield* __asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function* () { yield 1; }); })()))); }); } }; //// [O6.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const o6 = { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["await", 1]; + const x = yield __await(1); }); } }; //// [O7.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const o7 = { f() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js index abb3f0ca074..b5069bcea2c 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js @@ -71,18 +71,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var o1 = { f: function () { @@ -121,18 +120,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var o2 = { f: function () { @@ -140,7 +138,7 @@ var o2 = { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield"]]; + case 0: return [4 /*yield*/]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -177,18 +175,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var o3 = { f: function () { @@ -196,7 +193,7 @@ var o3 = { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -233,28 +230,27 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; @@ -272,8 +268,9 @@ var o4 = { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator([1]))]; - case 1: + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: x = _a.sent(); return [2 /*return*/]; } @@ -309,29 +306,28 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } +}; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); @@ -348,15 +344,16 @@ var o5 = { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: _a.sent(); return [2 /*return*/]; } - }); }); })()))]; - case 1: + }); }); })())))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: x = _a.sent(); return [2 /*return*/]; } @@ -392,18 +389,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var o6 = { f: function () { @@ -411,7 +407,7 @@ var o6 = { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["await", 1]]; + case 0: return [4 /*yield*/, __await(1)]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -448,18 +444,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var o7 = { f: function () { diff --git a/tests/baselines/reference/emitter.forAwait.es2015.js b/tests/baselines/reference/emitter.forAwait.es2015.js index 4bba2d06dcc..d88ed8d1a06 100644 --- a/tests/baselines/reference/emitter.forAwait.es2015.js +++ b/tests/baselines/reference/emitter.forAwait.es2015.js @@ -43,8 +43,8 @@ function f1() { return __awaiter(this, void 0, void 0, function* () { let y; try { - for (var y_1 = __asyncValues(y), y_1_1 = yield y_1.next(); !y_1_1.done; y_1_1 = yield y_1.next()) { - const x = y_1_1.value; + for (var y_1 = __asyncValues(y), y_1_1; y_1_1 = yield y_1.next(), !y_1_1.done;) { + const x = yield y_1_1.value; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } @@ -75,8 +75,8 @@ function f2() { return __awaiter(this, void 0, void 0, function* () { let x, y; try { - for (var y_1 = __asyncValues(y), y_1_1 = yield y_1.next(); !y_1_1.done; y_1_1 = yield y_1.next()) { - x = y_1_1.value; + for (var y_1 = __asyncValues(y), y_1_1; y_1_1 = yield y_1.next(), !y_1_1.done;) { + x = yield y_1_1.value; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } @@ -95,31 +95,30 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f3() { return __asyncGenerator(this, arguments, function* f3_1() { let y; try { - for (var y_1 = __asyncValues(y), y_1_1 = yield ["await", y_1.next()]; !y_1_1.done; y_1_1 = yield ["await", y_1.next()]) { - const x = y_1_1.value; + for (var y_1 = __asyncValues(y), y_1_1; y_1_1 = yield __await(y_1.next()), !y_1_1.done;) { + const x = yield __await(y_1_1.value); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { - if (y_1_1 && !y_1_1.done && (_a = y_1.return)) yield ["await", _a.call(y_1)]; + if (y_1_1 && !y_1_1.done && (_a = y_1.return)) yield __await(_a.call(y_1)); } finally { if (e_1) throw e_1.error; } } @@ -132,31 +131,30 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f4() { return __asyncGenerator(this, arguments, function* f4_1() { let x, y; try { - for (var y_1 = __asyncValues(y), y_1_1 = yield ["await", y_1.next()]; !y_1_1.done; y_1_1 = yield ["await", y_1.next()]) { - x = y_1_1.value; + for (var y_1 = __asyncValues(y), y_1_1; y_1_1 = yield __await(y_1.next()), !y_1_1.done;) { + x = yield __await(y_1_1.value); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { - if (y_1_1 && !y_1_1.done && (_a = y_1.return)) yield ["await", _a.call(y_1)]; + if (y_1_1 && !y_1_1.done && (_a = y_1.return)) yield __await(_a.call(y_1)); } finally { if (e_1) throw e_1.error; } } diff --git a/tests/baselines/reference/emitter.forAwait.es5.js b/tests/baselines/reference/emitter.forAwait.es5.js index 09b73ed21f0..fc8f5fd321d 100644 --- a/tests/baselines/reference/emitter.forAwait.es5.js +++ b/tests/baselines/reference/emitter.forAwait.es5.js @@ -74,18 +74,15 @@ function f1() { case 0: _b.trys.push([0, 6, 7, 12]); y_1 = __asyncValues(y); - return [4 /*yield*/, y_1.next()]; - case 1: - y_1_1 = _b.sent(); - _b.label = 2; + _b.label = 1; + case 1: return [4 /*yield*/, y_1.next()]; case 2: - if (!!y_1_1.done) return [3 /*break*/, 5]; - x = y_1_1.value; - _b.label = 3; - case 3: return [4 /*yield*/, y_1.next()]; - case 4: - y_1_1 = _b.sent(); - return [3 /*break*/, 2]; + if (!(y_1_1 = _b.sent(), !y_1_1.done)) return [3 /*break*/, 5]; + return [4 /*yield*/, y_1_1.value]; + case 3: + x = _b.sent(); + _b.label = 4; + case 4: return [3 /*break*/, 1]; case 5: return [3 /*break*/, 12]; case 6: e_1_1 = _b.sent(); @@ -157,18 +154,15 @@ function f2() { case 0: _b.trys.push([0, 6, 7, 12]); y_1 = __asyncValues(y); - return [4 /*yield*/, y_1.next()]; - case 1: - y_1_1 = _b.sent(); - _b.label = 2; + _b.label = 1; + case 1: return [4 /*yield*/, y_1.next()]; case 2: - if (!!y_1_1.done) return [3 /*break*/, 5]; - x = y_1_1.value; - _b.label = 3; - case 3: return [4 /*yield*/, y_1.next()]; - case 4: - y_1_1 = _b.sent(); - return [3 /*break*/, 2]; + if (!(y_1_1 = _b.sent(), !y_1_1.done)) return [3 /*break*/, 5]; + return [4 /*yield*/, y_1_1.value]; + case 3: + x = _b.sent(); + _b.label = 4; + case 4: return [3 /*break*/, 1]; case 5: return [3 /*break*/, 12]; case 6: e_1_1 = _b.sent(); @@ -224,18 +218,17 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f3() { return __asyncGenerator(this, arguments, function f3_1() { @@ -245,18 +238,15 @@ function f3() { case 0: _b.trys.push([0, 6, 7, 12]); y_1 = __asyncValues(y); - return [4 /*yield*/, ["await", y_1.next()]]; - case 1: - y_1_1 = _b.sent(); - _b.label = 2; + _b.label = 1; + case 1: return [4 /*yield*/, __await(y_1.next())]; case 2: - if (!!y_1_1.done) return [3 /*break*/, 5]; - x = y_1_1.value; - _b.label = 3; - case 3: return [4 /*yield*/, ["await", y_1.next()]]; - case 4: - y_1_1 = _b.sent(); - return [3 /*break*/, 2]; + if (!(y_1_1 = _b.sent(), !y_1_1.done)) return [3 /*break*/, 5]; + return [4 /*yield*/, __await(y_1_1.value)]; + case 3: + x = _b.sent(); + _b.label = 4; + case 4: return [3 /*break*/, 1]; case 5: return [3 /*break*/, 12]; case 6: e_1_1 = _b.sent(); @@ -265,7 +255,7 @@ function f3() { case 7: _b.trys.push([7, , 10, 11]); if (!(y_1_1 && !y_1_1.done && (_a = y_1.return))) return [3 /*break*/, 9]; - return [4 /*yield*/, ["await", _a.call(y_1)]]; + return [4 /*yield*/, __await(_a.call(y_1))]; case 8: _b.sent(); _b.label = 9; @@ -312,18 +302,17 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f4() { return __asyncGenerator(this, arguments, function f4_1() { @@ -333,18 +322,15 @@ function f4() { case 0: _b.trys.push([0, 6, 7, 12]); y_1 = __asyncValues(y); - return [4 /*yield*/, ["await", y_1.next()]]; - case 1: - y_1_1 = _b.sent(); - _b.label = 2; + _b.label = 1; + case 1: return [4 /*yield*/, __await(y_1.next())]; case 2: - if (!!y_1_1.done) return [3 /*break*/, 5]; - x = y_1_1.value; - _b.label = 3; - case 3: return [4 /*yield*/, ["await", y_1.next()]]; - case 4: - y_1_1 = _b.sent(); - return [3 /*break*/, 2]; + if (!(y_1_1 = _b.sent(), !y_1_1.done)) return [3 /*break*/, 5]; + return [4 /*yield*/, __await(y_1_1.value)]; + case 3: + x = _b.sent(); + _b.label = 4; + case 4: return [3 /*break*/, 1]; case 5: return [3 /*break*/, 12]; case 6: e_1_1 = _b.sent(); @@ -353,7 +339,7 @@ function f4() { case 7: _b.trys.push([7, , 10, 11]); if (!(y_1_1 && !y_1_1.done && (_a = y_1.return))) return [3 /*break*/, 9]; - return [4 /*yield*/, ["await", _a.call(y_1)]]; + return [4 /*yield*/, __await(_a.call(y_1))]; case 8: _b.sent(); _b.label = 9; diff --git a/tests/baselines/reference/emptyTypeArgumentList.errors.txt b/tests/baselines/reference/emptyTypeArgumentList.errors.txt index 9f252b127a1..036f307447b 100644 --- a/tests/baselines/reference/emptyTypeArgumentList.errors.txt +++ b/tests/baselines/reference/emptyTypeArgumentList.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/emptyTypeArgumentList.ts(2,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/emptyTypeArgumentList.ts(2,1): error TS2558: Expected 1 type arguments, but got 0. tests/cases/compiler/emptyTypeArgumentList.ts(2,4): error TS1099: Type argument list cannot be empty. @@ -6,6 +6,6 @@ tests/cases/compiler/emptyTypeArgumentList.ts(2,4): error TS1099: Type argument function foo() { } foo<>(); ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 1 type arguments, but got 0. ~~ !!! error TS1099: Type argument list cannot be empty. \ No newline at end of file diff --git a/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt b/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt index 799e35d0d47..648aa7c6c50 100644 --- a/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt +++ b/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,1): error TS2558: Expected 1 type arguments, but got 0. tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,8): error TS1099: Type argument list cannot be empty. @@ -6,6 +6,6 @@ tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,8): error TS1099: Type ar class foo { } new foo<>(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 1 type arguments, but got 0. ~~ !!! error TS1099: Type argument list cannot be empty. \ No newline at end of file diff --git a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5.types b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5.types index c61c80c5b3d..7db78f29829 100644 --- a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5.types +++ b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5.types @@ -61,7 +61,7 @@ } function f({} = a, [] = a, { p: {} = a} = a) { ->f : ({}?: any, []?: any, {p: {}}?: any) => ({}?: any, []?: any, {p: {}}?: any) => any +>f : ({}?: any, []?: any, { p: {} }?: any) => ({}?: any, []?: any, { p: {} }?: any) => any >a : any >a : any >p : any @@ -69,7 +69,7 @@ >a : any return ({} = a, [] = a, { p: {} = a } = a) => a; ->({} = a, [] = a, { p: {} = a } = a) => a : ({}?: any, []?: any, {p: {}}?: any) => any +>({} = a, [] = a, { p: {} = a } = a) => a : ({}?: any, []?: any, { p: {} }?: any) => any >a : any >a : any >p : any diff --git a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5iterable.types b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5iterable.types index 9c623fd8879..d5559047aba 100644 --- a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5iterable.types +++ b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5iterable.types @@ -61,7 +61,7 @@ } function f({} = a, [] = a, { p: {} = a} = a) { ->f : ({}?: any, []?: any, {p: {}}?: any) => ({}?: any, []?: any, {p: {}}?: any) => any +>f : ({}?: any, []?: any, { p: {} }?: any) => ({}?: any, []?: any, { p: {} }?: any) => any >a : any >a : any >p : any @@ -69,7 +69,7 @@ >a : any return ({} = a, [] = a, { p: {} = a } = a) => a; ->({} = a, [] = a, { p: {} = a } = a) => a : ({}?: any, []?: any, {p: {}}?: any) => any +>({} = a, [] = a, { p: {} = a } = a) => a : ({}?: any, []?: any, { p: {} }?: any) => any >a : any >a : any >p : any diff --git a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES6.types b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES6.types index 48d5f40b971..535562296a3 100644 --- a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES6.types +++ b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES6.types @@ -61,7 +61,7 @@ } function f({} = a, [] = a, { p: {} = a} = a) { ->f : ({}?: any, []?: any, {p: {}}?: any) => ({}?: any, []?: any, {p: {}}?: any) => any +>f : ({}?: any, []?: any, { p: {} }?: any) => ({}?: any, []?: any, { p: {} }?: any) => any >a : any >a : any >p : any @@ -69,7 +69,7 @@ >a : any return ({} = a, [] = a, { p: {} = a } = a) => a; ->({} = a, [] = a, { p: {} = a } = a) => a : ({}?: any, []?: any, {p: {}}?: any) => any +>({} = a, [] = a, { p: {} = a } = a) => a : ({}?: any, []?: any, { p: {} }?: any) => any >a : any >a : any >p : any diff --git a/tests/baselines/reference/enumAssignmentCompat3.errors.txt b/tests/baselines/reference/enumAssignmentCompat3.errors.txt index 558540c32c8..a458733bcc2 100644 --- a/tests/baselines/reference/enumAssignmentCompat3.errors.txt +++ b/tests/baselines/reference/enumAssignmentCompat3.errors.txt @@ -1,15 +1,19 @@ -tests/cases/compiler/enumAssignmentCompat3.ts(68,1): error TS2324: Property 'd' is missing in type 'First.E'. +tests/cases/compiler/enumAssignmentCompat3.ts(68,1): error TS2322: Type 'Abcd.E' is not assignable to type 'First.E'. + Property 'd' is missing in type 'First.E'. tests/cases/compiler/enumAssignmentCompat3.ts(70,1): error TS2322: Type 'Cd.E' is not assignable to type 'First.E'. Property 'd' is missing in type 'First.E'. tests/cases/compiler/enumAssignmentCompat3.ts(71,1): error TS2322: Type 'Nope' is not assignable to type 'E'. tests/cases/compiler/enumAssignmentCompat3.ts(72,1): error TS2322: Type 'Decl.E' is not assignable to type 'First.E'. -tests/cases/compiler/enumAssignmentCompat3.ts(75,1): error TS2324: Property 'c' is missing in type 'Ab.E'. +tests/cases/compiler/enumAssignmentCompat3.ts(75,1): error TS2322: Type 'First.E' is not assignable to type 'Ab.E'. + Property 'c' is missing in type 'Ab.E'. tests/cases/compiler/enumAssignmentCompat3.ts(76,1): error TS2322: Type 'First.E' is not assignable to type 'Cd.E'. + Property 'a' is missing in type 'Cd.E'. tests/cases/compiler/enumAssignmentCompat3.ts(77,1): error TS2322: Type 'E' is not assignable to type 'Nope'. tests/cases/compiler/enumAssignmentCompat3.ts(78,1): error TS2322: Type 'First.E' is not assignable to type 'Decl.E'. tests/cases/compiler/enumAssignmentCompat3.ts(82,1): error TS2322: Type 'Const.E' is not assignable to type 'First.E'. tests/cases/compiler/enumAssignmentCompat3.ts(83,1): error TS2322: Type 'First.E' is not assignable to type 'Const.E'. -tests/cases/compiler/enumAssignmentCompat3.ts(86,1): error TS2324: Property 'd' is missing in type 'First.E'. +tests/cases/compiler/enumAssignmentCompat3.ts(86,1): error TS2322: Type 'Merged.E' is not assignable to type 'First.E'. + Property 'd' is missing in type 'First.E'. ==== tests/cases/compiler/enumAssignmentCompat3.ts (11 errors) ==== @@ -82,7 +86,8 @@ tests/cases/compiler/enumAssignmentCompat3.ts(86,1): error TS2324: Property 'd' abc = secondAbc; // ok abc = secondAbcd; // missing 'd' ~~~ -!!! error TS2324: Property 'd' is missing in type 'First.E'. +!!! error TS2322: Type 'Abcd.E' is not assignable to type 'First.E'. +!!! error TS2322: Property 'd' is missing in type 'First.E'. abc = secondAb; // ok abc = secondCd; // missing 'd' ~~~ @@ -98,10 +103,12 @@ tests/cases/compiler/enumAssignmentCompat3.ts(86,1): error TS2324: Property 'd' secondAbcd = abc; // ok secondAb = abc; // missing 'c' ~~~~~~~~ -!!! error TS2324: Property 'c' is missing in type 'Ab.E'. +!!! error TS2322: Type 'First.E' is not assignable to type 'Ab.E'. +!!! error TS2322: Property 'c' is missing in type 'Ab.E'. secondCd = abc; // missing 'a' and 'b' ~~~~~~~~ !!! error TS2322: Type 'First.E' is not assignable to type 'Cd.E'. +!!! error TS2322: Property 'a' is missing in type 'Cd.E'. nope = abc; // nope! ~~~~ !!! error TS2322: Type 'E' is not assignable to type 'Nope'. @@ -121,7 +128,8 @@ tests/cases/compiler/enumAssignmentCompat3.ts(86,1): error TS2324: Property 'd' // merged enums compare all their members abc = merged; // missing 'd' ~~~ -!!! error TS2324: Property 'd' is missing in type 'First.E'. +!!! error TS2322: Type 'Merged.E' is not assignable to type 'First.E'. +!!! error TS2322: Property 'd' is missing in type 'First.E'. merged = abc; // ok abc = merged2; // ok merged2 = abc; // ok \ No newline at end of file diff --git a/tests/baselines/reference/enumBasics.errors.txt b/tests/baselines/reference/enumBasics.errors.txt deleted file mode 100644 index 4d82402b8ee..00000000000 --- a/tests/baselines/reference/enumBasics.errors.txt +++ /dev/null @@ -1,86 +0,0 @@ -tests/cases/conformance/enums/enumBasics.ts(13,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'e' must be of type 'typeof E1', but here has type '{ readonly [n: number]: string; readonly A: E1; readonly B: E1; readonly C: E1; }'. - - -==== tests/cases/conformance/enums/enumBasics.ts (1 errors) ==== - // Enum without initializers have first member = 0 and successive members = N + 1 - enum E1 { - A, - B, - C - } - - // Enum type is a subtype of Number - var x: number = E1.A; - - // Enum object type is anonymous with properties of the enum type and numeric indexer - var e = E1; - var e: { - ~ -!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'e' must be of type 'typeof E1', but here has type '{ readonly [n: number]: string; readonly A: E1; readonly B: E1; readonly C: E1; }'. - readonly A: E1; - readonly B: E1; - readonly C: E1; - readonly [n: number]: string; - }; - var e: typeof E1; - - // Reverse mapping of enum returns string name of property - var s = E1[e.A]; - var s: string; - - - // Enum with only constant members - enum E2 { - A = 1, B = 2, C = 3 - } - - // Enum with only computed members - enum E3 { - X = 'foo'.length, Y = 4 + 3, Z = +'foo' - } - - // Enum with constant members followed by computed members - enum E4 { - X = 0, Y, Z = 'foo'.length - } - - // Enum with > 2 constant members with no initializer for first member, non zero initializer for second element - enum E5 { - A, - B = 3, - C // 4 - } - - enum E6 { - A, - B = 0, - C // 1 - } - - // Enum with computed member initializer of type 'any' - enum E7 { - A = 'foo'['foo'] - } - - // Enum with computed member initializer of type number - enum E8 { - B = 'foo'['foo'] - } - - //Enum with computed member intializer of same enum type - enum E9 { - A, - B = A - } - - // (refer to .js to validate) - // Enum constant members are propagated - var doNotPropagate = [ - E8.B, E7.A, E4.Z, E3.X, E3.Y, E3.Z - ]; - // Enum computed members are not propagated - var doPropagate = [ - E9.A, E9.B, E6.B, E6.C, E6.A, E5.A, E5.B, E5.C - ]; - - \ No newline at end of file diff --git a/tests/baselines/reference/enumBasics.js b/tests/baselines/reference/enumBasics.js index 4ac41c0f3d1..3db9bc566c3 100644 --- a/tests/baselines/reference/enumBasics.js +++ b/tests/baselines/reference/enumBasics.js @@ -12,9 +12,9 @@ var x: number = E1.A; // Enum object type is anonymous with properties of the enum type and numeric indexer var e = E1; var e: { - readonly A: E1; - readonly B: E1; - readonly C: E1; + readonly A: E1.A; + readonly B: E1.B; + readonly C: E1.C; readonly [n: number]: string; }; var e: typeof E1; diff --git a/tests/baselines/reference/enumBasics.symbols b/tests/baselines/reference/enumBasics.symbols index ce81a80ca5f..948c1711837 100644 --- a/tests/baselines/reference/enumBasics.symbols +++ b/tests/baselines/reference/enumBasics.symbols @@ -28,17 +28,20 @@ var e = E1; var e: { >e : Symbol(e, Decl(enumBasics.ts, 11, 3), Decl(enumBasics.ts, 12, 3), Decl(enumBasics.ts, 18, 3)) - readonly A: E1; + readonly A: E1.A; >A : Symbol(A, Decl(enumBasics.ts, 12, 8)) >E1 : Symbol(E1, Decl(enumBasics.ts, 0, 0)) +>A : Symbol(E1.A, Decl(enumBasics.ts, 1, 9)) - readonly B: E1; ->B : Symbol(B, Decl(enumBasics.ts, 13, 19)) + readonly B: E1.B; +>B : Symbol(B, Decl(enumBasics.ts, 13, 21)) >E1 : Symbol(E1, Decl(enumBasics.ts, 0, 0)) +>B : Symbol(E1.B, Decl(enumBasics.ts, 2, 6)) - readonly C: E1; ->C : Symbol(C, Decl(enumBasics.ts, 14, 19)) + readonly C: E1.C; +>C : Symbol(C, Decl(enumBasics.ts, 14, 21)) >E1 : Symbol(E1, Decl(enumBasics.ts, 0, 0)) +>C : Symbol(E1.C, Decl(enumBasics.ts, 3, 6)) readonly [n: number]: string; >n : Symbol(n, Decl(enumBasics.ts, 16, 14)) diff --git a/tests/baselines/reference/enumBasics.types b/tests/baselines/reference/enumBasics.types index 9e68b06bc3e..c2e1ac94fdf 100644 --- a/tests/baselines/reference/enumBasics.types +++ b/tests/baselines/reference/enumBasics.types @@ -4,21 +4,21 @@ enum E1 { >E1 : E1 A, ->A : E1 +>A : E1.A B, ->B : E1 +>B : E1.B C ->C : E1 +>C : E1.C } // Enum type is a subtype of Number var x: number = E1.A; >x : number ->E1.A : E1 +>E1.A : E1.A >E1 : typeof E1 ->A : E1 +>A : E1.A // Enum object type is anonymous with properties of the enum type and numeric indexer var e = E1; @@ -28,17 +28,20 @@ var e = E1; var e: { >e : typeof E1 - readonly A: E1; ->A : E1 ->E1 : E1 + readonly A: E1.A; +>A : E1.A +>E1 : any +>A : E1.A - readonly B: E1; ->B : E1 ->E1 : E1 + readonly B: E1.B; +>B : E1.B +>E1 : any +>B : E1.B - readonly C: E1; ->C : E1 ->E1 : E1 + readonly C: E1.C; +>C : E1.C +>E1 : any +>C : E1.C readonly [n: number]: string; >n : number @@ -53,9 +56,9 @@ var s = E1[e.A]; >s : string >E1[e.A] : string >E1 : typeof E1 ->e.A : E1 +>e.A : E1.A >e : typeof E1 ->A : E1 +>A : E1.A var s: string; >s : string @@ -66,12 +69,12 @@ enum E2 { >E2 : E2 A = 1, B = 2, C = 3 ->A : E2 ->1 : number ->B : E2 ->2 : number ->C : E2 ->3 : number +>A : E2.A +>1 : 1 +>B : E2.B +>2 : 2 +>C : E2.C +>3 : 3 } // Enum with only computed members @@ -81,15 +84,15 @@ enum E3 { X = 'foo'.length, Y = 4 + 3, Z = +'foo' >X : E3 >'foo'.length : number ->'foo' : string +>'foo' : "foo" >length : number >Y : E3 >4 + 3 : number ->4 : number ->3 : number +>4 : 4 +>3 : 3 >Z : E3 >+'foo' : number ->'foo' : string +>'foo' : "foo" } // Enum with constant members followed by computed members @@ -98,11 +101,11 @@ enum E4 { X = 0, Y, Z = 'foo'.length >X : E4 ->0 : number +>0 : 0 >Y : E4 >Z : E4 >'foo'.length : number ->'foo' : string +>'foo' : "foo" >length : number } @@ -111,28 +114,28 @@ enum E5 { >E5 : E5 A, ->A : E5 +>A : E5.A B = 3, ->B : E5 ->3 : number +>B : E5.B +>3 : 3 C // 4 ->C : E5 +>C : E5.C } enum E6 { >E6 : E6 A, ->A : E6 +>A : E6.A B = 0, ->B : E6 ->0 : number +>B : E6.A +>0 : 0 C // 1 ->C : E6 +>C : E6.C } // Enum with computed member initializer of type 'any' @@ -142,8 +145,8 @@ enum E7 { A = 'foo'['foo'] >A : E7 >'foo'['foo'] : any ->'foo' : string ->'foo' : string +>'foo' : "foo" +>'foo' : "foo" } // Enum with computed member initializer of type number @@ -153,8 +156,8 @@ enum E8 { B = 'foo'['foo'] >B : E8 >'foo'['foo'] : any ->'foo' : string ->'foo' : string +>'foo' : "foo" +>'foo' : "foo" } //Enum with computed member intializer of same enum type @@ -198,8 +201,8 @@ var doNotPropagate = [ ]; // Enum computed members are not propagated var doPropagate = [ ->doPropagate : (E5 | E6 | E9)[] ->[ E9.A, E9.B, E6.B, E6.C, E6.A, E5.A, E5.B, E5.C] : (E5 | E6 | E9)[] +>doPropagate : (E9 | E6 | E5)[] +>[ E9.A, E9.B, E6.B, E6.C, E6.A, E5.A, E5.B, E5.C] : (E9 | E6 | E5)[] E9.A, E9.B, E6.B, E6.C, E6.A, E5.A, E5.B, E5.C >E9.A : E9 @@ -208,24 +211,24 @@ var doPropagate = [ >E9.B : E9 >E9 : typeof E9 >B : E9 ->E6.B : E6 +>E6.B : E6.A >E6 : typeof E6 ->B : E6 ->E6.C : E6 +>B : E6.A +>E6.C : E6.C >E6 : typeof E6 ->C : E6 ->E6.A : E6 +>C : E6.C +>E6.A : E6.A >E6 : typeof E6 ->A : E6 ->E5.A : E5 +>A : E6.A +>E5.A : E5.A >E5 : typeof E5 ->A : E5 ->E5.B : E5 +>A : E5.A +>E5.B : E5.B >E5 : typeof E5 ->B : E5 ->E5.C : E5 +>B : E5.B +>E5.C : E5.C >E5 : typeof E5 ->C : E5 +>C : E5.C ]; diff --git a/tests/baselines/reference/enumClassification.js b/tests/baselines/reference/enumClassification.js new file mode 100644 index 00000000000..0a046dc60d2 --- /dev/null +++ b/tests/baselines/reference/enumClassification.js @@ -0,0 +1,218 @@ +//// [enumClassification.ts] +// An enum type where each member has no initializer or an initializer that specififes +// a numeric literal, a string literal, or a single identifier naming another member in +// the enum type is classified as a literal enum type. An enum type that doesn't adhere +// to this pattern is classified as a numeric enum type. + +// Examples of literal enum types + +enum E01 { + A +} + +enum E02 { + A = 123 +} + +enum E03 { + A = "hello" +} + +enum E04 { + A, + B, + C +} + +enum E05 { + A, + B = 10, + C +} + +enum E06 { + A = "one", + B = "two", + C = "three" +} + +enum E07 { + A, + B, + C = "hi", + D = 10, + E, + F = "bye" +} + +enum E08 { + A = 10, + B = "hello", + C = A, + D = B, + E = C, +} + +// Examples of numeric enum types with only constant members + +enum E10 {} + +enum E11 { + A = +0, + B, + C +} + +enum E12 { + A = 1 << 0, + B = 1 << 1, + C = 1 << 2 +} + +// Examples of numeric enum types with constant and computed members + +enum E20 { + A = "foo".length, + B = A + 1, + C = +"123", + D = Math.sin(1) +} + + +//// [enumClassification.js] +// An enum type where each member has no initializer or an initializer that specififes +// a numeric literal, a string literal, or a single identifier naming another member in +// the enum type is classified as a literal enum type. An enum type that doesn't adhere +// to this pattern is classified as a numeric enum type. +// Examples of literal enum types +var E01; +(function (E01) { + E01[E01["A"] = 0] = "A"; +})(E01 || (E01 = {})); +var E02; +(function (E02) { + E02[E02["A"] = 123] = "A"; +})(E02 || (E02 = {})); +var E03; +(function (E03) { + E03["A"] = "hello"; +})(E03 || (E03 = {})); +var E04; +(function (E04) { + E04[E04["A"] = 0] = "A"; + E04[E04["B"] = 1] = "B"; + E04[E04["C"] = 2] = "C"; +})(E04 || (E04 = {})); +var E05; +(function (E05) { + E05[E05["A"] = 0] = "A"; + E05[E05["B"] = 10] = "B"; + E05[E05["C"] = 11] = "C"; +})(E05 || (E05 = {})); +var E06; +(function (E06) { + E06["A"] = "one"; + E06["B"] = "two"; + E06["C"] = "three"; +})(E06 || (E06 = {})); +var E07; +(function (E07) { + E07[E07["A"] = 0] = "A"; + E07[E07["B"] = 1] = "B"; + E07["C"] = "hi"; + E07[E07["D"] = 10] = "D"; + E07[E07["E"] = 11] = "E"; + E07["F"] = "bye"; +})(E07 || (E07 = {})); +var E08; +(function (E08) { + E08[E08["A"] = 10] = "A"; + E08["B"] = "hello"; + E08[E08["C"] = 10] = "C"; + E08["D"] = "hello"; + E08[E08["E"] = 10] = "E"; +})(E08 || (E08 = {})); +// Examples of numeric enum types with only constant members +var E10; +(function (E10) { +})(E10 || (E10 = {})); +var E11; +(function (E11) { + E11[E11["A"] = 0] = "A"; + E11[E11["B"] = 1] = "B"; + E11[E11["C"] = 2] = "C"; +})(E11 || (E11 = {})); +var E12; +(function (E12) { + E12[E12["A"] = 1] = "A"; + E12[E12["B"] = 2] = "B"; + E12[E12["C"] = 4] = "C"; +})(E12 || (E12 = {})); +// Examples of numeric enum types with constant and computed members +var E20; +(function (E20) { + E20[E20["A"] = "foo".length] = "A"; + E20[E20["B"] = E20.A + 1] = "B"; + E20[E20["C"] = +"123"] = "C"; + E20[E20["D"] = Math.sin(1)] = "D"; +})(E20 || (E20 = {})); + + +//// [enumClassification.d.ts] +declare enum E01 { + A = 0, +} +declare enum E02 { + A = 123, +} +declare enum E03 { + A = "hello", +} +declare enum E04 { + A = 0, + B = 1, + C = 2, +} +declare enum E05 { + A = 0, + B = 10, + C = 11, +} +declare enum E06 { + A = "one", + B = "two", + C = "three", +} +declare enum E07 { + A = 0, + B = 1, + C = "hi", + D = 10, + E = 11, + F = "bye", +} +declare enum E08 { + A = 10, + B = "hello", + C = 10, + D = "hello", + E = 10, +} +declare enum E10 { +} +declare enum E11 { + A = 0, + B = 1, + C = 2, +} +declare enum E12 { + A = 1, + B = 2, + C = 4, +} +declare enum E20 { + A, + B, + C, + D, +} diff --git a/tests/baselines/reference/enumClassification.symbols b/tests/baselines/reference/enumClassification.symbols new file mode 100644 index 00000000000..119162e26a1 --- /dev/null +++ b/tests/baselines/reference/enumClassification.symbols @@ -0,0 +1,167 @@ +=== tests/cases/conformance/enums/enumClassification.ts === +// An enum type where each member has no initializer or an initializer that specififes +// a numeric literal, a string literal, or a single identifier naming another member in +// the enum type is classified as a literal enum type. An enum type that doesn't adhere +// to this pattern is classified as a numeric enum type. + +// Examples of literal enum types + +enum E01 { +>E01 : Symbol(E01, Decl(enumClassification.ts, 0, 0)) + + A +>A : Symbol(E01.A, Decl(enumClassification.ts, 7, 10)) +} + +enum E02 { +>E02 : Symbol(E02, Decl(enumClassification.ts, 9, 1)) + + A = 123 +>A : Symbol(E02.A, Decl(enumClassification.ts, 11, 10)) +} + +enum E03 { +>E03 : Symbol(E03, Decl(enumClassification.ts, 13, 1)) + + A = "hello" +>A : Symbol(E03.A, Decl(enumClassification.ts, 15, 10)) +} + +enum E04 { +>E04 : Symbol(E04, Decl(enumClassification.ts, 17, 1)) + + A, +>A : Symbol(E04.A, Decl(enumClassification.ts, 19, 10)) + + B, +>B : Symbol(E04.B, Decl(enumClassification.ts, 20, 6)) + + C +>C : Symbol(E04.C, Decl(enumClassification.ts, 21, 6)) +} + +enum E05 { +>E05 : Symbol(E05, Decl(enumClassification.ts, 23, 1)) + + A, +>A : Symbol(E05.A, Decl(enumClassification.ts, 25, 10)) + + B = 10, +>B : Symbol(E05.B, Decl(enumClassification.ts, 26, 6)) + + C +>C : Symbol(E05.C, Decl(enumClassification.ts, 27, 11)) +} + +enum E06 { +>E06 : Symbol(E06, Decl(enumClassification.ts, 29, 1)) + + A = "one", +>A : Symbol(E06.A, Decl(enumClassification.ts, 31, 10)) + + B = "two", +>B : Symbol(E06.B, Decl(enumClassification.ts, 32, 14)) + + C = "three" +>C : Symbol(E06.C, Decl(enumClassification.ts, 33, 14)) +} + +enum E07 { +>E07 : Symbol(E07, Decl(enumClassification.ts, 35, 1)) + + A, +>A : Symbol(E07.A, Decl(enumClassification.ts, 37, 10)) + + B, +>B : Symbol(E07.B, Decl(enumClassification.ts, 38, 6)) + + C = "hi", +>C : Symbol(E07.C, Decl(enumClassification.ts, 39, 6)) + + D = 10, +>D : Symbol(E07.D, Decl(enumClassification.ts, 40, 13)) + + E, +>E : Symbol(E07.E, Decl(enumClassification.ts, 41, 11)) + + F = "bye" +>F : Symbol(E07.F, Decl(enumClassification.ts, 42, 6)) +} + +enum E08 { +>E08 : Symbol(E08, Decl(enumClassification.ts, 44, 1)) + + A = 10, +>A : Symbol(E08.A, Decl(enumClassification.ts, 46, 10)) + + B = "hello", +>B : Symbol(E08.B, Decl(enumClassification.ts, 47, 11)) + + C = A, +>C : Symbol(E08.C, Decl(enumClassification.ts, 48, 16)) +>A : Symbol(E08.A, Decl(enumClassification.ts, 46, 10)) + + D = B, +>D : Symbol(E08.D, Decl(enumClassification.ts, 49, 10)) +>B : Symbol(E08.B, Decl(enumClassification.ts, 47, 11)) + + E = C, +>E : Symbol(E08.E, Decl(enumClassification.ts, 50, 10)) +>C : Symbol(E08.C, Decl(enumClassification.ts, 48, 16)) +} + +// Examples of numeric enum types with only constant members + +enum E10 {} +>E10 : Symbol(E10, Decl(enumClassification.ts, 52, 1)) + +enum E11 { +>E11 : Symbol(E11, Decl(enumClassification.ts, 56, 11)) + + A = +0, +>A : Symbol(E11.A, Decl(enumClassification.ts, 58, 10)) + + B, +>B : Symbol(E11.B, Decl(enumClassification.ts, 59, 11)) + + C +>C : Symbol(E11.C, Decl(enumClassification.ts, 60, 6)) +} + +enum E12 { +>E12 : Symbol(E12, Decl(enumClassification.ts, 62, 1)) + + A = 1 << 0, +>A : Symbol(E12.A, Decl(enumClassification.ts, 64, 10)) + + B = 1 << 1, +>B : Symbol(E12.B, Decl(enumClassification.ts, 65, 15)) + + C = 1 << 2 +>C : Symbol(E12.C, Decl(enumClassification.ts, 66, 15)) +} + +// Examples of numeric enum types with constant and computed members + +enum E20 { +>E20 : Symbol(E20, Decl(enumClassification.ts, 68, 1)) + + A = "foo".length, +>A : Symbol(E20.A, Decl(enumClassification.ts, 72, 10)) +>"foo".length : Symbol(String.length, Decl(lib.d.ts, --, --)) +>length : Symbol(String.length, Decl(lib.d.ts, --, --)) + + B = A + 1, +>B : Symbol(E20.B, Decl(enumClassification.ts, 73, 21)) +>A : Symbol(E20.A, Decl(enumClassification.ts, 72, 10)) + + C = +"123", +>C : Symbol(E20.C, Decl(enumClassification.ts, 74, 14)) + + D = Math.sin(1) +>D : Symbol(E20.D, Decl(enumClassification.ts, 75, 15)) +>Math.sin : Symbol(Math.sin, Decl(lib.d.ts, --, --)) +>Math : Symbol(Math, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>sin : Symbol(Math.sin, Decl(lib.d.ts, --, --)) +} + diff --git a/tests/baselines/reference/enumClassification.types b/tests/baselines/reference/enumClassification.types new file mode 100644 index 00000000000..d0581c7fcae --- /dev/null +++ b/tests/baselines/reference/enumClassification.types @@ -0,0 +1,196 @@ +=== tests/cases/conformance/enums/enumClassification.ts === +// An enum type where each member has no initializer or an initializer that specififes +// a numeric literal, a string literal, or a single identifier naming another member in +// the enum type is classified as a literal enum type. An enum type that doesn't adhere +// to this pattern is classified as a numeric enum type. + +// Examples of literal enum types + +enum E01 { +>E01 : E01 + + A +>A : E01 +} + +enum E02 { +>E02 : E02 + + A = 123 +>A : E02 +>123 : 123 +} + +enum E03 { +>E03 : E03 + + A = "hello" +>A : E03 +>"hello" : "hello" +} + +enum E04 { +>E04 : E04 + + A, +>A : E04.A + + B, +>B : E04.B + + C +>C : E04.C +} + +enum E05 { +>E05 : E05 + + A, +>A : E05.A + + B = 10, +>B : E05.B +>10 : 10 + + C +>C : E05.C +} + +enum E06 { +>E06 : E06 + + A = "one", +>A : E06.A +>"one" : "one" + + B = "two", +>B : E06.B +>"two" : "two" + + C = "three" +>C : E06.C +>"three" : "three" +} + +enum E07 { +>E07 : E07 + + A, +>A : E07.A + + B, +>B : E07.B + + C = "hi", +>C : E07.C +>"hi" : "hi" + + D = 10, +>D : E07.D +>10 : 10 + + E, +>E : E07.E + + F = "bye" +>F : E07.F +>"bye" : "bye" +} + +enum E08 { +>E08 : E08 + + A = 10, +>A : E08.A +>10 : 10 + + B = "hello", +>B : E08.B +>"hello" : "hello" + + C = A, +>C : E08.A +>A : E08.A + + D = B, +>D : E08.B +>B : E08.B + + E = C, +>E : E08.A +>C : E08.A +} + +// Examples of numeric enum types with only constant members + +enum E10 {} +>E10 : E10 + +enum E11 { +>E11 : E11 + + A = +0, +>A : E11 +>+0 : number +>0 : 0 + + B, +>B : E11 + + C +>C : E11 +} + +enum E12 { +>E12 : E12 + + A = 1 << 0, +>A : E12 +>1 << 0 : number +>1 : 1 +>0 : 0 + + B = 1 << 1, +>B : E12 +>1 << 1 : number +>1 : 1 +>1 : 1 + + C = 1 << 2 +>C : E12 +>1 << 2 : number +>1 : 1 +>2 : 2 +} + +// Examples of numeric enum types with constant and computed members + +enum E20 { +>E20 : E20 + + A = "foo".length, +>A : E20 +>"foo".length : number +>"foo" : "foo" +>length : number + + B = A + 1, +>B : E20 +>A + 1 : number +>A : E20 +>1 : 1 + + C = +"123", +>C : E20 +>+"123" : number +>"123" : "123" + + D = Math.sin(1) +>D : E20 +>Math.sin(1) : number +>Math.sin : (x: number) => number +>Math : Math +>sin : (x: number) => number +>1 : 1 +} + diff --git a/tests/baselines/reference/enumErrors.errors.txt b/tests/baselines/reference/enumErrors.errors.txt index 3efa042ff38..af719d47ae2 100644 --- a/tests/baselines/reference/enumErrors.errors.txt +++ b/tests/baselines/reference/enumErrors.errors.txt @@ -3,13 +3,17 @@ tests/cases/conformance/enums/enumErrors.ts(3,6): error TS2431: Enum name cannot tests/cases/conformance/enums/enumErrors.ts(4,6): error TS2431: Enum name cannot be 'string'. tests/cases/conformance/enums/enumErrors.ts(5,6): error TS2431: Enum name cannot be 'boolean'. tests/cases/conformance/enums/enumErrors.ts(9,9): error TS2322: Type 'Number' is not assignable to type 'E5'. -tests/cases/conformance/enums/enumErrors.ts(26,9): error TS2322: Type '""' is not assignable to type 'E11'. +tests/cases/conformance/enums/enumErrors.ts(26,9): error TS2322: Type 'true' is not assignable to type 'E11'. tests/cases/conformance/enums/enumErrors.ts(27,9): error TS2322: Type 'Date' is not assignable to type 'E11'. tests/cases/conformance/enums/enumErrors.ts(28,9): error TS2304: Cannot find name 'window'. tests/cases/conformance/enums/enumErrors.ts(29,9): error TS2322: Type '{}' is not assignable to type 'E11'. +tests/cases/conformance/enums/enumErrors.ts(35,9): error TS2553: Computed values are not permitted in an enum with string valued members. +tests/cases/conformance/enums/enumErrors.ts(36,9): error TS2553: Computed values are not permitted in an enum with string valued members. +tests/cases/conformance/enums/enumErrors.ts(37,9): error TS2553: Computed values are not permitted in an enum with string valued members. +tests/cases/conformance/enums/enumErrors.ts(38,9): error TS2553: Computed values are not permitted in an enum with string valued members. -==== tests/cases/conformance/enums/enumErrors.ts (9 errors) ==== +==== tests/cases/conformance/enums/enumErrors.ts (13 errors) ==== // Enum named with PredefinedTypes enum any { } ~~~ @@ -45,9 +49,9 @@ tests/cases/conformance/enums/enumErrors.ts(29,9): error TS2322: Type '{}' is no // Enum with computed member intializer of other types enum E11 { - A = '', - ~~ -!!! error TS2322: Type '""' is not assignable to type 'E11'. + A = true, + ~~~~ +!!! error TS2322: Type 'true' is not assignable to type 'E11'. B = new Date(), ~~~~~~~~~~ !!! error TS2322: Type 'Date' is not assignable to type 'E11'. @@ -58,4 +62,21 @@ tests/cases/conformance/enums/enumErrors.ts(29,9): error TS2322: Type '{}' is no ~~ !!! error TS2322: Type '{}' is not assignable to type 'E11'. } + + // Enum with string valued member and computed member initializers + enum E12 { + A = '', + B = new Date(), + ~~~~~~~~~~ +!!! error TS2553: Computed values are not permitted in an enum with string valued members. + C = window, + ~~~~~~ +!!! error TS2553: Computed values are not permitted in an enum with string valued members. + D = {}, + ~~ +!!! error TS2553: Computed values are not permitted in an enum with string valued members. + E = 1 + 1, + ~~~~~ +!!! error TS2553: Computed values are not permitted in an enum with string valued members. + } \ No newline at end of file diff --git a/tests/baselines/reference/enumErrors.js b/tests/baselines/reference/enumErrors.js index a8ecdf2470a..17b67864c70 100644 --- a/tests/baselines/reference/enumErrors.js +++ b/tests/baselines/reference/enumErrors.js @@ -24,11 +24,20 @@ enum E10 { // Enum with computed member intializer of other types enum E11 { - A = '', + A = true, B = new Date(), C = window, D = {} } + +// Enum with string valued member and computed member initializers +enum E12 { + A = '', + B = new Date(), + C = window, + D = {}, + E = 1 + 1, +} //// [enumErrors.js] @@ -65,8 +74,17 @@ var E10; // Enum with computed member intializer of other types var E11; (function (E11) { - E11[E11["A"] = ''] = "A"; + E11[E11["A"] = true] = "A"; E11[E11["B"] = new Date()] = "B"; E11[E11["C"] = window] = "C"; E11[E11["D"] = {}] = "D"; })(E11 || (E11 = {})); +// Enum with string valued member and computed member initializers +var E12; +(function (E12) { + E12["A"] = ""; + E12[E12["B"] = 0] = "B"; + E12[E12["C"] = 0] = "C"; + E12[E12["D"] = 0] = "D"; + E12[E12["E"] = 0] = "E"; +})(E12 || (E12 = {})); diff --git a/tests/baselines/reference/enumUsedBeforeDeclaration.errors.txt b/tests/baselines/reference/enumUsedBeforeDeclaration.errors.txt index aea5366389b..64e1830b521 100644 --- a/tests/baselines/reference/enumUsedBeforeDeclaration.errors.txt +++ b/tests/baselines/reference/enumUsedBeforeDeclaration.errors.txt @@ -1,14 +1,11 @@ tests/cases/compiler/enumUsedBeforeDeclaration.ts(1,18): error TS2450: Enum 'Color' used before its declaration. -tests/cases/compiler/enumUsedBeforeDeclaration.ts(2,24): error TS2450: Enum 'ConstColor' used before its declaration. -==== tests/cases/compiler/enumUsedBeforeDeclaration.ts (2 errors) ==== +==== tests/cases/compiler/enumUsedBeforeDeclaration.ts (1 errors) ==== const v: Color = Color.Green; ~~~~~ !!! error TS2450: Enum 'Color' used before its declaration. const v2: ConstColor = ConstColor.Green; - ~~~~~~~~~~ -!!! error TS2450: Enum 'ConstColor' used before its declaration. enum Color { Red, Green, Blue } const enum ConstColor { Red, Green, Blue } diff --git a/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt b/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt index f0976ba7398..27e8791f5d2 100644 --- a/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt +++ b/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts(4,14): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts(4,14): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts (1 errors) ==== @@ -7,7 +7,7 @@ tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts(4,14): error T function f() { var d1 = new derived(); ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var d2 = new derived(4); } diff --git a/tests/baselines/reference/errorLocationForInterfaceExtension.errors.txt b/tests/baselines/reference/errorLocationForInterfaceExtension.errors.txt index f385d0afcb3..6ed1517335d 100644 --- a/tests/baselines/reference/errorLocationForInterfaceExtension.errors.txt +++ b/tests/baselines/reference/errorLocationForInterfaceExtension.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/errorLocationForInterfaceExtension.ts(3,21): error TS2304: Cannot find name 'string'. +tests/cases/compiler/errorLocationForInterfaceExtension.ts(3,21): error TS2693: 'string' only refers to a type, but is being used as a value here. ==== tests/cases/compiler/errorLocationForInterfaceExtension.ts (1 errors) ==== @@ -6,5 +6,5 @@ tests/cases/compiler/errorLocationForInterfaceExtension.ts(3,21): error TS2304: interface x extends string { } ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. \ No newline at end of file diff --git a/tests/baselines/reference/errorMessageOnObjectLiteralType.errors.txt b/tests/baselines/reference/errorMessageOnObjectLiteralType.errors.txt index bf9006a7143..7dffc9053e3 100644 --- a/tests/baselines/reference/errorMessageOnObjectLiteralType.errors.txt +++ b/tests/baselines/reference/errorMessageOnObjectLiteralType.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/errorMessageOnObjectLiteralType.ts(5,3): error TS2339: Property 'getOwnPropertyNamess' does not exist on type '{ a: string; b: number; }'. -tests/cases/compiler/errorMessageOnObjectLiteralType.ts(6,8): error TS2339: Property 'getOwnPropertyNamess' does not exist on type 'ObjectConstructor'. +tests/cases/compiler/errorMessageOnObjectLiteralType.ts(6,8): error TS2551: Property 'getOwnPropertyNamess' does not exist on type 'ObjectConstructor'. Did you mean 'getOwnPropertyNames'? ==== tests/cases/compiler/errorMessageOnObjectLiteralType.ts (2 errors) ==== @@ -12,4 +12,4 @@ tests/cases/compiler/errorMessageOnObjectLiteralType.ts(6,8): error TS2339: Prop !!! error TS2339: Property 'getOwnPropertyNamess' does not exist on type '{ a: string; b: number; }'. Object.getOwnPropertyNamess(null); ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2339: Property 'getOwnPropertyNamess' does not exist on type 'ObjectConstructor'. \ No newline at end of file +!!! error TS2551: Property 'getOwnPropertyNamess' does not exist on type 'ObjectConstructor'. Did you mean 'getOwnPropertyNames'? \ No newline at end of file diff --git a/tests/baselines/reference/es5ExportDefaultExpression.js b/tests/baselines/reference/es5ExportDefaultExpression.js index 3db562da647..b365018b2f3 100644 --- a/tests/baselines/reference/es5ExportDefaultExpression.js +++ b/tests/baselines/reference/es5ExportDefaultExpression.js @@ -9,5 +9,5 @@ exports.default = (1 + 2); //// [es5ExportDefaultExpression.d.ts] -declare var _default: number; +declare const _default: number; export default _default; diff --git a/tests/baselines/reference/es6ExportDefaultExpression.js b/tests/baselines/reference/es6ExportDefaultExpression.js index ce6dcd71b90..059aae49598 100644 --- a/tests/baselines/reference/es6ExportDefaultExpression.js +++ b/tests/baselines/reference/es6ExportDefaultExpression.js @@ -7,5 +7,5 @@ export default (1 + 2); //// [es6ExportDefaultExpression.d.ts] -declare var _default: number; +declare const _default: number; export default _default; diff --git a/tests/baselines/reference/es6ExportEqualsInterop.errors.txt b/tests/baselines/reference/es6ExportEqualsInterop.errors.txt index 4a9f7dcb506..4675136d081 100644 --- a/tests/baselines/reference/es6ExportEqualsInterop.errors.txt +++ b/tests/baselines/reference/es6ExportEqualsInterop.errors.txt @@ -14,11 +14,20 @@ tests/cases/compiler/main.ts(36,8): error TS1192: Module '"class-module"' has no tests/cases/compiler/main.ts(39,21): error TS2497: Module '"interface"' resolves to a non-module entity and cannot be imported using this construct. tests/cases/compiler/main.ts(45,21): error TS2497: Module '"function"' resolves to a non-module entity and cannot be imported using this construct. tests/cases/compiler/main.ts(47,21): error TS2497: Module '"class"' resolves to a non-module entity and cannot be imported using this construct. +tests/cases/compiler/main.ts(50,1): error TS2693: 'y1' only refers to a type, but is being used as a value here. +tests/cases/compiler/main.ts(56,4): error TS2339: Property 'a' does not exist on type '() => any'. +tests/cases/compiler/main.ts(58,4): error TS2339: Property 'a' does not exist on type 'typeof Foo'. +tests/cases/compiler/main.ts(62,10): error TS2305: Module '"interface"' has no exported member 'a'. tests/cases/compiler/main.ts(62,25): error TS2497: Module '"interface"' resolves to a non-module entity and cannot be imported using this construct. +tests/cases/compiler/main.ts(68,10): error TS2305: Module '"function"' has no exported member 'a'. tests/cases/compiler/main.ts(68,25): error TS2497: Module '"function"' resolves to a non-module entity and cannot be imported using this construct. +tests/cases/compiler/main.ts(70,10): error TS2305: Module '"class"' has no exported member 'a'. tests/cases/compiler/main.ts(70,25): error TS2497: Module '"class"' resolves to a non-module entity and cannot be imported using this construct. +tests/cases/compiler/main.ts(85,10): error TS2305: Module '"interface"' has no exported member 'a'. tests/cases/compiler/main.ts(85,25): error TS2497: Module '"interface"' resolves to a non-module entity and cannot be imported using this construct. +tests/cases/compiler/main.ts(91,10): error TS2305: Module '"function"' has no exported member 'a'. tests/cases/compiler/main.ts(91,25): error TS2497: Module '"function"' resolves to a non-module entity and cannot be imported using this construct. +tests/cases/compiler/main.ts(93,10): error TS2305: Module '"class"' has no exported member 'a'. tests/cases/compiler/main.ts(93,25): error TS2497: Module '"class"' resolves to a non-module entity and cannot be imported using this construct. tests/cases/compiler/main.ts(97,15): error TS2498: Module '"interface"' uses 'export =' and cannot be used with 'export *'. tests/cases/compiler/main.ts(98,15): error TS2498: Module '"variable"' uses 'export =' and cannot be used with 'export *'. @@ -32,7 +41,7 @@ tests/cases/compiler/main.ts(105,15): error TS2498: Module '"class"' uses 'expor tests/cases/compiler/main.ts(106,15): error TS2498: Module '"class-module"' uses 'export =' and cannot be used with 'export *'. -==== tests/cases/compiler/main.ts (32 errors) ==== +==== tests/cases/compiler/main.ts (41 errors) ==== /// // import-equals @@ -115,18 +124,26 @@ tests/cases/compiler/main.ts(106,15): error TS2498: Module '"class-module"' uses import * as y0 from "class-module"; y1.a; + ~~ +!!! error TS2693: 'y1' only refers to a type, but is being used as a value here. y2.a; y3.a; y4.a; y5.a; y6.a; y7.a; + ~ +!!! error TS2339: Property 'a' does not exist on type '() => any'. y8.a; y9.a; + ~ +!!! error TS2339: Property 'a' does not exist on type 'typeof Foo'. y0.a; // named import import { a as a1 } from "interface"; + ~ +!!! error TS2305: Module '"interface"' has no exported member 'a'. ~~~~~~~~~~~ !!! error TS2497: Module '"interface"' resolves to a non-module entity and cannot be imported using this construct. import { a as a2 } from "variable"; @@ -135,10 +152,14 @@ tests/cases/compiler/main.ts(106,15): error TS2498: Module '"class-module"' uses import { a as a5 } from "interface-module"; import { a as a6 } from "variable-module"; import { a as a7 } from "function"; + ~ +!!! error TS2305: Module '"function"' has no exported member 'a'. ~~~~~~~~~~ !!! error TS2497: Module '"function"' resolves to a non-module entity and cannot be imported using this construct. import { a as a8 } from "function-module"; import { a as a9 } from "class"; + ~ +!!! error TS2305: Module '"class"' has no exported member 'a'. ~~~~~~~ !!! error TS2497: Module '"class"' resolves to a non-module entity and cannot be imported using this construct. import { a as a0 } from "class-module"; @@ -156,6 +177,8 @@ tests/cases/compiler/main.ts(106,15): error TS2498: Module '"class-module"' uses // named export export { a as a1 } from "interface"; + ~ +!!! error TS2305: Module '"interface"' has no exported member 'a'. ~~~~~~~~~~~ !!! error TS2497: Module '"interface"' resolves to a non-module entity and cannot be imported using this construct. export { a as a2 } from "variable"; @@ -164,10 +187,14 @@ tests/cases/compiler/main.ts(106,15): error TS2498: Module '"class-module"' uses export { a as a5 } from "interface-module"; export { a as a6 } from "variable-module"; export { a as a7 } from "function"; + ~ +!!! error TS2305: Module '"function"' has no exported member 'a'. ~~~~~~~~~~ !!! error TS2497: Module '"function"' resolves to a non-module entity and cannot be imported using this construct. export { a as a8 } from "function-module"; export { a as a9 } from "class"; + ~ +!!! error TS2305: Module '"class"' has no exported member 'a'. ~~~~~~~ !!! error TS2497: Module '"class"' resolves to a non-module entity and cannot be imported using this construct. export { a as a0 } from "class-module"; diff --git a/tests/baselines/reference/es6ExportEqualsInterop.js b/tests/baselines/reference/es6ExportEqualsInterop.js index 5e04221df8b..13908a29e2d 100644 --- a/tests/baselines/reference/es6ExportEqualsInterop.js +++ b/tests/baselines/reference/es6ExportEqualsInterop.js @@ -232,8 +232,6 @@ z7.a; z8.a; z9.a; z0.a; -// namespace import -var y1 = require("interface"); var y2 = require("variable"); var y3 = require("interface-variable"); var y4 = require("module"); diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport.js index bccb0a9dea4..a5b7700c36c 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport.js @@ -48,6 +48,6 @@ var x1 = es6ImportDefaultBindingFollowedWithNamedImport_0_5.m; export declare var a: number; export declare var x: number; export declare var m: number; -declare var _default: {}; +declare const _default: {}; export default _default; //// [es6ImportDefaultBindingFollowedWithNamedImport_1.d.ts] diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportWithExport.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportWithExport.js index 756ae6a999b..ff8c1059ad1 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportWithExport.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportWithExport.js @@ -47,7 +47,7 @@ define(["require", "exports", "server", "server", "server", "server", "server"], export declare var a: number; export declare var x: number; export declare var m: number; -declare var _default: {}; +declare const _default: {}; export default _default; //// [client.d.ts] export declare var x1: number; diff --git a/tests/baselines/reference/escapedIdentifiers.types b/tests/baselines/reference/escapedIdentifiers.types index 6d48bb3392f..ef6c0983d39 100644 --- a/tests/baselines/reference/escapedIdentifiers.types +++ b/tests/baselines/reference/escapedIdentifiers.types @@ -220,7 +220,7 @@ class testClass { >testClass : testClass public func(arg1: number, arg\u0032: string, arg\u0033: boolean, arg4: number) { ->func : (arg1: number, arg\u0032: string, arg\u0033: boolean, arg4: number) => void +>func : (arg1: number, arg2: string, arg3: boolean, arg4: number) => void >arg1 : number >arg\u0032 : string >arg\u0033 : boolean diff --git a/tests/baselines/reference/exportClassExtendingIntersection.errors.txt b/tests/baselines/reference/exportClassExtendingIntersection.errors.txt deleted file mode 100644 index eb94869fdc2..00000000000 --- a/tests/baselines/reference/exportClassExtendingIntersection.errors.txt +++ /dev/null @@ -1,39 +0,0 @@ -tests/cases/compiler/FinalClass.ts(4,14): error TS4093: 'extends' clause of exported class 'MyExtendedClass' refers to a type whose name cannot be referenced. - - -==== tests/cases/compiler/BaseClass.ts (0 errors) ==== - export type Constructor = new (...args: any[]) => T; - - export class MyBaseClass { - baseProperty: string; - constructor(value: T) {} - } -==== tests/cases/compiler/MixinClass.ts (0 errors) ==== - import { Constructor, MyBaseClass } from './BaseClass'; - - export interface MyMixin { - mixinProperty: string; - } - - export function MyMixin>>(base: T): T & Constructor { - return class extends base { - mixinProperty: string; - } - } -==== tests/cases/compiler/FinalClass.ts (1 errors) ==== - import { MyBaseClass } from './BaseClass'; - import { MyMixin } from './MixinClass'; - - export class MyExtendedClass extends MyMixin(MyBaseClass) { - ~~~~~~~~~~~~~~~ -!!! error TS4093: 'extends' clause of exported class 'MyExtendedClass' refers to a type whose name cannot be referenced. - extendedClassProperty: number; - } -==== tests/cases/compiler/Main.ts (0 errors) ==== - import { MyExtendedClass } from './FinalClass'; - import { MyMixin } from './MixinClass'; - - const myExtendedClass = new MyExtendedClass('string'); - - const AnotherMixedClass = MyMixin(MyExtendedClass); - \ No newline at end of file diff --git a/tests/baselines/reference/exportClassExtendingIntersection.js b/tests/baselines/reference/exportClassExtendingIntersection.js index 2309a9af9b6..919f1695093 100644 --- a/tests/baselines/reference/exportClassExtendingIntersection.js +++ b/tests/baselines/reference/exportClassExtendingIntersection.js @@ -111,4 +111,11 @@ export interface MyMixin { mixinProperty: string; } export declare function MyMixin>>(base: T): T & Constructor; +//// [FinalClass.d.ts] +import { MyBaseClass } from './BaseClass'; +import { MyMixin } from './MixinClass'; +declare const MyExtendedClass_base: typeof MyBaseClass & (new (...args: any[]) => MyMixin); +export declare class MyExtendedClass extends MyExtendedClass_base { + extendedClassProperty: number; +} //// [Main.d.ts] diff --git a/tests/baselines/reference/exportClassExtendingIntersection.symbols b/tests/baselines/reference/exportClassExtendingIntersection.symbols new file mode 100644 index 00000000000..b22febb7d72 --- /dev/null +++ b/tests/baselines/reference/exportClassExtendingIntersection.symbols @@ -0,0 +1,79 @@ +=== tests/cases/compiler/BaseClass.ts === +export type Constructor = new (...args: any[]) => T; +>Constructor : Symbol(Constructor, Decl(BaseClass.ts, 0, 0)) +>T : Symbol(T, Decl(BaseClass.ts, 0, 24)) +>args : Symbol(args, Decl(BaseClass.ts, 0, 34)) +>T : Symbol(T, Decl(BaseClass.ts, 0, 24)) + +export class MyBaseClass { +>MyBaseClass : Symbol(MyBaseClass, Decl(BaseClass.ts, 0, 55)) +>T : Symbol(T, Decl(BaseClass.ts, 2, 25)) + + baseProperty: string; +>baseProperty : Symbol(MyBaseClass.baseProperty, Decl(BaseClass.ts, 2, 29)) + + constructor(value: T) {} +>value : Symbol(value, Decl(BaseClass.ts, 4, 16)) +>T : Symbol(T, Decl(BaseClass.ts, 2, 25)) +} +=== tests/cases/compiler/MixinClass.ts === +import { Constructor, MyBaseClass } from './BaseClass'; +>Constructor : Symbol(Constructor, Decl(MixinClass.ts, 0, 8)) +>MyBaseClass : Symbol(MyBaseClass, Decl(MixinClass.ts, 0, 21)) + +export interface MyMixin { +>MyMixin : Symbol(MyMixin, Decl(MixinClass.ts, 0, 55), Decl(MixinClass.ts, 4, 1)) + + mixinProperty: string; +>mixinProperty : Symbol(MyMixin.mixinProperty, Decl(MixinClass.ts, 2, 26)) +} + +export function MyMixin>>(base: T): T & Constructor { +>MyMixin : Symbol(MyMixin, Decl(MixinClass.ts, 0, 55), Decl(MixinClass.ts, 4, 1)) +>T : Symbol(T, Decl(MixinClass.ts, 6, 24)) +>Constructor : Symbol(Constructor, Decl(MixinClass.ts, 0, 8)) +>MyBaseClass : Symbol(MyBaseClass, Decl(MixinClass.ts, 0, 21)) +>base : Symbol(base, Decl(MixinClass.ts, 6, 65)) +>T : Symbol(T, Decl(MixinClass.ts, 6, 24)) +>T : Symbol(T, Decl(MixinClass.ts, 6, 24)) +>Constructor : Symbol(Constructor, Decl(MixinClass.ts, 0, 8)) +>MyMixin : Symbol(MyMixin, Decl(MixinClass.ts, 0, 55), Decl(MixinClass.ts, 4, 1)) + + return class extends base { +>base : Symbol(base, Decl(MixinClass.ts, 6, 65)) + + mixinProperty: string; +>mixinProperty : Symbol((Anonymous class).mixinProperty, Decl(MixinClass.ts, 7, 31)) + } +} +=== tests/cases/compiler/FinalClass.ts === +import { MyBaseClass } from './BaseClass'; +>MyBaseClass : Symbol(MyBaseClass, Decl(FinalClass.ts, 0, 8)) + +import { MyMixin } from './MixinClass'; +>MyMixin : Symbol(MyMixin, Decl(FinalClass.ts, 1, 8)) + +export class MyExtendedClass extends MyMixin(MyBaseClass) { +>MyExtendedClass : Symbol(MyExtendedClass, Decl(FinalClass.ts, 1, 39)) +>MyMixin : Symbol(MyMixin, Decl(FinalClass.ts, 1, 8)) +>MyBaseClass : Symbol(MyBaseClass, Decl(FinalClass.ts, 0, 8)) + + extendedClassProperty: number; +>extendedClassProperty : Symbol(MyExtendedClass.extendedClassProperty, Decl(FinalClass.ts, 3, 67)) +} +=== tests/cases/compiler/Main.ts === +import { MyExtendedClass } from './FinalClass'; +>MyExtendedClass : Symbol(MyExtendedClass, Decl(Main.ts, 0, 8)) + +import { MyMixin } from './MixinClass'; +>MyMixin : Symbol(MyMixin, Decl(Main.ts, 1, 8)) + +const myExtendedClass = new MyExtendedClass('string'); +>myExtendedClass : Symbol(myExtendedClass, Decl(Main.ts, 3, 5)) +>MyExtendedClass : Symbol(MyExtendedClass, Decl(Main.ts, 0, 8)) + +const AnotherMixedClass = MyMixin(MyExtendedClass); +>AnotherMixedClass : Symbol(AnotherMixedClass, Decl(Main.ts, 5, 5)) +>MyMixin : Symbol(MyMixin, Decl(Main.ts, 1, 8)) +>MyExtendedClass : Symbol(MyExtendedClass, Decl(Main.ts, 0, 8)) + diff --git a/tests/baselines/reference/exportClassExtendingIntersection.types b/tests/baselines/reference/exportClassExtendingIntersection.types new file mode 100644 index 00000000000..5840c53a056 --- /dev/null +++ b/tests/baselines/reference/exportClassExtendingIntersection.types @@ -0,0 +1,84 @@ +=== tests/cases/compiler/BaseClass.ts === +export type Constructor = new (...args: any[]) => T; +>Constructor : Constructor +>T : T +>args : any[] +>T : T + +export class MyBaseClass { +>MyBaseClass : MyBaseClass +>T : T + + baseProperty: string; +>baseProperty : string + + constructor(value: T) {} +>value : T +>T : T +} +=== tests/cases/compiler/MixinClass.ts === +import { Constructor, MyBaseClass } from './BaseClass'; +>Constructor : any +>MyBaseClass : typeof MyBaseClass + +export interface MyMixin { +>MyMixin : MyMixin + + mixinProperty: string; +>mixinProperty : string +} + +export function MyMixin>>(base: T): T & Constructor { +>MyMixin : >>(base: T) => T & Constructor +>T : T +>Constructor : Constructor +>MyBaseClass : MyBaseClass +>base : T +>T : T +>T : T +>Constructor : Constructor +>MyMixin : MyMixin + + return class extends base { +>class extends base { mixinProperty: string; } : { new (...args: any[]): (Anonymous class); prototype: MyMixin.(Anonymous class); } & T +>base : MyBaseClass + + mixinProperty: string; +>mixinProperty : string + } +} +=== tests/cases/compiler/FinalClass.ts === +import { MyBaseClass } from './BaseClass'; +>MyBaseClass : typeof MyBaseClass + +import { MyMixin } from './MixinClass'; +>MyMixin : MyBaseClass>(base: T) => T & (new (...args: any[]) => MyMixin) + +export class MyExtendedClass extends MyMixin(MyBaseClass) { +>MyExtendedClass : MyExtendedClass +>MyMixin(MyBaseClass) : MyBaseClass & MyMixin +>MyMixin : MyBaseClass>(base: T) => T & (new (...args: any[]) => MyMixin) +>MyBaseClass : typeof MyBaseClass + + extendedClassProperty: number; +>extendedClassProperty : number +} +=== tests/cases/compiler/Main.ts === +import { MyExtendedClass } from './FinalClass'; +>MyExtendedClass : typeof MyExtendedClass + +import { MyMixin } from './MixinClass'; +>MyMixin : MyBaseClass>(base: T) => T & (new (...args: any[]) => MyMixin) + +const myExtendedClass = new MyExtendedClass('string'); +>myExtendedClass : MyExtendedClass +>new MyExtendedClass('string') : MyExtendedClass +>MyExtendedClass : typeof MyExtendedClass +>'string' : "string" + +const AnotherMixedClass = MyMixin(MyExtendedClass); +>AnotherMixedClass : typeof MyExtendedClass & (new (...args: any[]) => MyMixin) +>MyMixin(MyExtendedClass) : typeof MyExtendedClass & (new (...args: any[]) => MyMixin) +>MyMixin : MyBaseClass>(base: T) => T & (new (...args: any[]) => MyMixin) +>MyExtendedClass : typeof MyExtendedClass + diff --git a/tests/baselines/reference/exportDefaultAbstractClass.js b/tests/baselines/reference/exportDefaultAbstractClass.js index c8dba03543d..38976311d63 100644 --- a/tests/baselines/reference/exportDefaultAbstractClass.js +++ b/tests/baselines/reference/exportDefaultAbstractClass.js @@ -1,14 +1,29 @@ //// [tests/cases/compiler/exportDefaultAbstractClass.ts] //// //// [a.ts] -export default abstract class A {} +export default abstract class A { a: number; } + +class B extends A {} +new B().a.toExponential(); //// [b.ts] -import A from './a' - +import A from './a'; + +class C extends A {} +new C().a.toExponential(); //// [a.js] "use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); exports.__esModule = true; var A = (function () { function A() { @@ -16,6 +31,33 @@ var A = (function () { return A; }()); exports["default"] = A; +var B = (function (_super) { + __extends(B, _super); + function B() { + return _super !== null && _super.apply(this, arguments) || this; + } + return B; +}(A)); +new B().a.toExponential(); //// [b.js] "use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); exports.__esModule = true; +var a_1 = require("./a"); +var C = (function (_super) { + __extends(C, _super); + function C() { + return _super !== null && _super.apply(this, arguments) || this; + } + return C; +}(a_1["default"])); +new C().a.toExponential(); diff --git a/tests/baselines/reference/exportDefaultAbstractClass.symbols b/tests/baselines/reference/exportDefaultAbstractClass.symbols index 75c6c068f08..27e42487f31 100644 --- a/tests/baselines/reference/exportDefaultAbstractClass.symbols +++ b/tests/baselines/reference/exportDefaultAbstractClass.symbols @@ -1,8 +1,31 @@ === tests/cases/compiler/a.ts === -export default abstract class A {} +export default abstract class A { a: number; } +>A : Symbol(A, Decl(a.ts, 0, 0)) +>a : Symbol(A.a, Decl(a.ts, 0, 33)) + +class B extends A {} +>B : Symbol(B, Decl(a.ts, 0, 46)) >A : Symbol(A, Decl(a.ts, 0, 0)) +new B().a.toExponential(); +>new B().a.toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) +>new B().a : Symbol(A.a, Decl(a.ts, 0, 33)) +>B : Symbol(B, Decl(a.ts, 0, 46)) +>a : Symbol(A.a, Decl(a.ts, 0, 33)) +>toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) + === tests/cases/compiler/b.ts === -import A from './a' +import A from './a'; >A : Symbol(A, Decl(b.ts, 0, 6)) +class C extends A {} +>C : Symbol(C, Decl(b.ts, 0, 20)) +>A : Symbol(A, Decl(b.ts, 0, 6)) + +new C().a.toExponential(); +>new C().a.toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) +>new C().a : Symbol(A.a, Decl(a.ts, 0, 33)) +>C : Symbol(C, Decl(b.ts, 0, 20)) +>a : Symbol(A.a, Decl(a.ts, 0, 33)) +>toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) + diff --git a/tests/baselines/reference/exportDefaultAbstractClass.types b/tests/baselines/reference/exportDefaultAbstractClass.types index d400be1af43..776ad01420a 100644 --- a/tests/baselines/reference/exportDefaultAbstractClass.types +++ b/tests/baselines/reference/exportDefaultAbstractClass.types @@ -1,8 +1,35 @@ === tests/cases/compiler/a.ts === -export default abstract class A {} +export default abstract class A { a: number; } +>A : A +>a : number + +class B extends A {} +>B : B >A : A +new B().a.toExponential(); +>new B().a.toExponential() : string +>new B().a.toExponential : (fractionDigits?: number) => string +>new B().a : number +>new B() : B +>B : typeof B +>a : number +>toExponential : (fractionDigits?: number) => string + === tests/cases/compiler/b.ts === -import A from './a' +import A from './a'; >A : typeof A +class C extends A {} +>C : C +>A : A + +new C().a.toExponential(); +>new C().a.toExponential() : string +>new C().a.toExponential : (fractionDigits?: number) => string +>new C().a : number +>new C() : C +>C : typeof C +>a : number +>toExponential : (fractionDigits?: number) => string + diff --git a/tests/baselines/reference/exportDefaultInterface.js b/tests/baselines/reference/exportDefaultInterface.js new file mode 100644 index 00000000000..e7b5c945e32 --- /dev/null +++ b/tests/baselines/reference/exportDefaultInterface.js @@ -0,0 +1,24 @@ +//// [tests/cases/compiler/exportDefaultInterface.ts] //// + +//// [a.ts] +export default interface A { value: number; } + +var a: A; +a.value.toExponential(); + +//// [b.ts] +import A from './a'; + +var a: A; +a.value.toExponential(); + +//// [a.js] +"use strict"; +exports.__esModule = true; +var a; +a.value.toExponential(); +//// [b.js] +"use strict"; +exports.__esModule = true; +var a; +a.value.toExponential(); diff --git a/tests/baselines/reference/exportDefaultInterface.symbols b/tests/baselines/reference/exportDefaultInterface.symbols new file mode 100644 index 00000000000..1a3b172fe97 --- /dev/null +++ b/tests/baselines/reference/exportDefaultInterface.symbols @@ -0,0 +1,31 @@ +=== tests/cases/compiler/a.ts === +export default interface A { value: number; } +>A : Symbol(A, Decl(a.ts, 0, 0)) +>value : Symbol(A.value, Decl(a.ts, 0, 28)) + +var a: A; +>a : Symbol(a, Decl(a.ts, 2, 3)) +>A : Symbol(A, Decl(a.ts, 0, 0)) + +a.value.toExponential(); +>a.value.toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) +>a.value : Symbol(A.value, Decl(a.ts, 0, 28)) +>a : Symbol(a, Decl(a.ts, 2, 3)) +>value : Symbol(A.value, Decl(a.ts, 0, 28)) +>toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) + +=== tests/cases/compiler/b.ts === +import A from './a'; +>A : Symbol(A, Decl(b.ts, 0, 6)) + +var a: A; +>a : Symbol(a, Decl(b.ts, 2, 3)) +>A : Symbol(A, Decl(b.ts, 0, 6)) + +a.value.toExponential(); +>a.value.toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) +>a.value : Symbol(A.value, Decl(a.ts, 0, 28)) +>a : Symbol(a, Decl(b.ts, 2, 3)) +>value : Symbol(A.value, Decl(a.ts, 0, 28)) +>toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) + diff --git a/tests/baselines/reference/exportDefaultInterface.types b/tests/baselines/reference/exportDefaultInterface.types new file mode 100644 index 00000000000..636197339f4 --- /dev/null +++ b/tests/baselines/reference/exportDefaultInterface.types @@ -0,0 +1,33 @@ +=== tests/cases/compiler/a.ts === +export default interface A { value: number; } +>A : A +>value : number + +var a: A; +>a : A +>A : A + +a.value.toExponential(); +>a.value.toExponential() : string +>a.value.toExponential : (fractionDigits?: number) => string +>a.value : number +>a : A +>value : number +>toExponential : (fractionDigits?: number) => string + +=== tests/cases/compiler/b.ts === +import A from './a'; +>A : any + +var a: A; +>a : A +>A : A + +a.value.toExponential(); +>a.value.toExponential() : string +>a.value.toExponential : (fractionDigits?: number) => string +>a.value : number +>a : A +>value : number +>toExponential : (fractionDigits?: number) => string + diff --git a/tests/baselines/reference/externModule.errors.txt b/tests/baselines/reference/externModule.errors.txt index 8d4126350c1..d6659c1d548 100644 --- a/tests/baselines/reference/externModule.errors.txt +++ b/tests/baselines/reference/externModule.errors.txt @@ -8,10 +8,10 @@ tests/cases/compiler/externModule.ts(18,6): error TS2390: Constructor implementa tests/cases/compiler/externModule.ts(20,13): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/compiler/externModule.ts(26,13): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/compiler/externModule.ts(28,13): error TS2391: Function implementation is missing or not immediately following the declaration. -tests/cases/compiler/externModule.ts(32,11): error TS2304: Cannot find name 'XDate'. -tests/cases/compiler/externModule.ts(34,7): error TS2304: Cannot find name 'XDate'. -tests/cases/compiler/externModule.ts(36,7): error TS2304: Cannot find name 'XDate'. -tests/cases/compiler/externModule.ts(37,3): error TS2304: Cannot find name 'XDate'. +tests/cases/compiler/externModule.ts(32,11): error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? +tests/cases/compiler/externModule.ts(34,7): error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? +tests/cases/compiler/externModule.ts(36,7): error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? +tests/cases/compiler/externModule.ts(37,3): error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? ==== tests/cases/compiler/externModule.ts (14 errors) ==== @@ -68,17 +68,17 @@ tests/cases/compiler/externModule.ts(37,3): error TS2304: Cannot find name 'XDat var d=new XDate(); ~~~~~ -!!! error TS2304: Cannot find name 'XDate'. +!!! error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? d.getDay(); d=new XDate(1978,2); ~~~~~ -!!! error TS2304: Cannot find name 'XDate'. +!!! error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? d.getXDate(); var n=XDate.parse("3/2/2004"); ~~~~~ -!!! error TS2304: Cannot find name 'XDate'. +!!! error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? n=XDate.UTC(1964,2,1); ~~~~~ -!!! error TS2304: Cannot find name 'XDate'. +!!! error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? \ No newline at end of file diff --git a/tests/baselines/reference/fallbackToBindingPatternForTypeInference.types b/tests/baselines/reference/fallbackToBindingPatternForTypeInference.types index 7b1a2d8e6ff..161870de77c 100644 --- a/tests/baselines/reference/fallbackToBindingPatternForTypeInference.types +++ b/tests/baselines/reference/fallbackToBindingPatternForTypeInference.types @@ -9,7 +9,7 @@ declare function trans(f: (x: T) => string): number; trans(({a}) => a); >trans(({a}) => a) : number >trans : (f: (x: T) => string) => number ->({a}) => a : ({a}: { a: any; }) => any +>({a}) => a : ({ a }: { a: any; }) => any >a : any >a : any @@ -24,7 +24,7 @@ trans(([b,c]) => 'foo'); trans(({d: [e,f]}) => 'foo'); >trans(({d: [e,f]}) => 'foo') : number >trans : (f: (x: T) => string) => number ->({d: [e,f]}) => 'foo' : ({d: [e, f]}: { d: [any, any]; }) => string +>({d: [e,f]}) => 'foo' : ({ d: [e, f] }: { d: [any, any]; }) => string >d : any >e : any >f : any @@ -33,7 +33,7 @@ trans(({d: [e,f]}) => 'foo'); trans(([{g},{h}]) => 'foo'); >trans(([{g},{h}]) => 'foo') : number >trans : (f: (x: T) => string) => number ->([{g},{h}]) => 'foo' : ([{g}, {h}]: [{ g: any; }, { h: any; }]) => string +>([{g},{h}]) => 'foo' : ([{ g }, { h }]: [{ g: any; }, { h: any; }]) => string >g : any >h : any >'foo' : "foo" @@ -41,7 +41,7 @@ trans(([{g},{h}]) => 'foo'); trans(({a, b = 10}) => a); >trans(({a, b = 10}) => a) : number >trans : (f: (x: T) => string) => number ->({a, b = 10}) => a : ({a, b}: { a: any; b?: number; }) => any +>({a, b = 10}) => a : ({ a, b }: { a: any; b?: number; }) => any >a : any >b : number >10 : 10 diff --git a/tests/baselines/reference/forwardRefInEnum.js b/tests/baselines/reference/forwardRefInEnum.js index 555454dccaa..592adbd2534 100644 --- a/tests/baselines/reference/forwardRefInEnum.js +++ b/tests/baselines/reference/forwardRefInEnum.js @@ -19,11 +19,11 @@ var E1; (function (E1) { // illegal case // forward reference to the element of the same enum - E1[E1["X"] = E1.Y] = "X"; - E1[E1["X1"] = E1["Y"]] = "X1"; + E1[E1["X"] = 0] = "X"; + E1[E1["X1"] = 0] = "X1"; // forward reference to the element of the same enum - E1[E1["Y"] = E1.Z] = "Y"; - E1[E1["Y1"] = E1["Z"]] = "Y1"; + E1[E1["Y"] = 0] = "Y"; + E1[E1["Y1"] = 0] = "Y1"; })(E1 || (E1 = {})); (function (E1) { E1[E1["Z"] = 4] = "Z"; diff --git a/tests/baselines/reference/functionCall11.errors.txt b/tests/baselines/reference/functionCall11.errors.txt index f1a5949acd7..e7dc72b1488 100644 --- a/tests/baselines/reference/functionCall11.errors.txt +++ b/tests/baselines/reference/functionCall11.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/functionCall11.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall11.ts(4,1): error TS2554: Expected 1-2 arguments, but got 0. tests/cases/compiler/functionCall11.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall11.ts(6,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall11.ts(6,1): error TS2554: Expected 1-2 arguments, but got 3. ==== tests/cases/compiler/functionCall11.ts (3 errors) ==== @@ -9,11 +9,11 @@ tests/cases/compiler/functionCall11.ts(6,1): error TS2346: Supplied parameters d foo('foo'); foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. foo('foo', 1, 'bar'); ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/functionCall12.errors.txt b/tests/baselines/reference/functionCall12.errors.txt index ef93a34b080..3c22d0dcef7 100644 --- a/tests/baselines/reference/functionCall12.errors.txt +++ b/tests/baselines/reference/functionCall12.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionCall12.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall12.ts(4,1): error TS2554: Expected 1-3 arguments, but got 0. tests/cases/compiler/functionCall12.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. tests/cases/compiler/functionCall12.ts(7,15): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. @@ -9,7 +9,7 @@ tests/cases/compiler/functionCall12.ts(7,15): error TS2345: Argument of type '3' foo('foo'); foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-3 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall13.errors.txt b/tests/baselines/reference/functionCall13.errors.txt index a89d7fc1efa..c53f63b7d78 100644 --- a/tests/baselines/reference/functionCall13.errors.txt +++ b/tests/baselines/reference/functionCall13.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionCall13.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall13.ts(4,1): error TS2555: Expected at least 1 arguments, but got 0. tests/cases/compiler/functionCall13.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. @@ -8,7 +8,7 @@ tests/cases/compiler/functionCall13.ts(5,5): error TS2345: Argument of type '1' foo('foo'); foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2555: Expected at least 1 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall16.errors.txt b/tests/baselines/reference/functionCall16.errors.txt index d338c1305dd..b3345d82779 100644 --- a/tests/baselines/reference/functionCall16.errors.txt +++ b/tests/baselines/reference/functionCall16.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/functionCall16.ts(2,12): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall16.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall16.ts(5,1): error TS2555: Expected at least 1 arguments, but got 0. tests/cases/compiler/functionCall16.ts(6,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. @@ -12,7 +12,7 @@ tests/cases/compiler/functionCall16.ts(6,5): error TS2345: Argument of type '1' foo('foo', 'bar'); foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2555: Expected at least 1 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall17.errors.txt b/tests/baselines/reference/functionCall17.errors.txt index f266554b518..c672c092677 100644 --- a/tests/baselines/reference/functionCall17.errors.txt +++ b/tests/baselines/reference/functionCall17.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/functionCall17.ts(2,12): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall17.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall17.ts(4,1): error TS2555: Expected at least 1 arguments, but got 0. tests/cases/compiler/functionCall17.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. tests/cases/compiler/functionCall17.ts(6,12): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. @@ -12,7 +12,7 @@ tests/cases/compiler/functionCall17.ts(6,12): error TS2345: Argument of type '1' foo('foo'); foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2555: Expected at least 1 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall6.errors.txt b/tests/baselines/reference/functionCall6.errors.txt index 3d590d8f5c2..5200a5a3e6f 100644 --- a/tests/baselines/reference/functionCall6.errors.txt +++ b/tests/baselines/reference/functionCall6.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/functionCall6.ts(3,5): error TS2345: Argument of type '2' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall6.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/functionCall6.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall6.ts(4,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/compiler/functionCall6.ts(5,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionCall6.ts (3 errors) ==== @@ -11,8 +11,8 @@ tests/cases/compiler/functionCall6.ts(5,1): error TS2346: Supplied parameters do !!! error TS2345: Argument of type '2' is not assignable to parameter of type 'string'. foo('foo', 'bar'); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/functionCall7.errors.txt b/tests/baselines/reference/functionCall7.errors.txt index 138c5f62f16..78f2a3384db 100644 --- a/tests/baselines/reference/functionCall7.errors.txt +++ b/tests/baselines/reference/functionCall7.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/functionCall7.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall7.ts(5,1): error TS2554: Expected 1 arguments, but got 2. tests/cases/compiler/functionCall7.ts(6,5): error TS2345: Argument of type '4' is not assignable to parameter of type 'c1'. -tests/cases/compiler/functionCall7.ts(7,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall7.ts(7,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionCall7.ts (3 errors) ==== @@ -10,11 +10,11 @@ tests/cases/compiler/functionCall7.ts(7,1): error TS2346: Supplied parameters do foo(myC); foo(myC, myC); ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. foo(4); ~ !!! error TS2345: Argument of type '4' is not assignable to parameter of type 'c1'. foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/functionCall8.errors.txt b/tests/baselines/reference/functionCall8.errors.txt index 7cf197d5812..86e01baa740 100644 --- a/tests/baselines/reference/functionCall8.errors.txt +++ b/tests/baselines/reference/functionCall8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionCall8.ts(3,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall8.ts(3,1): error TS2554: Expected 0-1 arguments, but got 2. tests/cases/compiler/functionCall8.ts(4,5): error TS2345: Argument of type '4' is not assignable to parameter of type 'string'. @@ -7,7 +7,7 @@ tests/cases/compiler/functionCall8.ts(4,5): error TS2345: Argument of type '4' i foo('foo'); foo('foo', 'bar'); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0-1 arguments, but got 2. foo(4); ~ !!! error TS2345: Argument of type '4' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall9.errors.txt b/tests/baselines/reference/functionCall9.errors.txt index 83cda64e204..50c33a15aad 100644 --- a/tests/baselines/reference/functionCall9.errors.txt +++ b/tests/baselines/reference/functionCall9.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/functionCall9.ts(4,11): error TS2345: Argument of type '"bar"' is not assignable to parameter of type 'number'. -tests/cases/compiler/functionCall9.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall9.ts(5,1): error TS2554: Expected 0-2 arguments, but got 3. ==== tests/cases/compiler/functionCall9.ts (2 errors) ==== @@ -11,5 +11,5 @@ tests/cases/compiler/functionCall9.ts(5,1): error TS2346: Supplied parameters do !!! error TS2345: Argument of type '"bar"' is not assignable to parameter of type 'number'. foo('foo', 1, 'bar'); ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0-2 arguments, but got 3. foo(); \ No newline at end of file diff --git a/tests/baselines/reference/functionCalls.errors.txt b/tests/baselines/reference/functionCalls.errors.txt index 85e75876779..8e84aa81e0e 100644 --- a/tests/baselines/reference/functionCalls.errors.txt +++ b/tests/baselines/reference/functionCalls.errors.txt @@ -1,6 +1,7 @@ tests/cases/conformance/expressions/functionCalls/functionCalls.ts(8,1): error TS2347: Untyped function calls may not accept type arguments. tests/cases/conformance/expressions/functionCalls/functionCalls.ts(9,1): error TS2347: Untyped function calls may not accept type arguments. tests/cases/conformance/expressions/functionCalls/functionCalls.ts(10,1): error TS2347: Untyped function calls may not accept type arguments. +tests/cases/conformance/expressions/functionCalls/functionCalls.ts(10,8): error TS2304: Cannot find name 'Window'. tests/cases/conformance/expressions/functionCalls/functionCalls.ts(25,1): error TS2347: Untyped function calls may not accept type arguments. tests/cases/conformance/expressions/functionCalls/functionCalls.ts(26,1): error TS2347: Untyped function calls may not accept type arguments. tests/cases/conformance/expressions/functionCalls/functionCalls.ts(27,1): error TS2347: Untyped function calls may not accept type arguments. @@ -9,7 +10,7 @@ tests/cases/conformance/expressions/functionCalls/functionCalls.ts(33,1): error tests/cases/conformance/expressions/functionCalls/functionCalls.ts(34,1): error TS2347: Untyped function calls may not accept type arguments. -==== tests/cases/conformance/expressions/functionCalls/functionCalls.ts (9 errors) ==== +==== tests/cases/conformance/expressions/functionCalls/functionCalls.ts (10 errors) ==== // Invoke function call on value of type 'any' with no type arguments var anyVar: any; anyVar(0); @@ -26,6 +27,8 @@ tests/cases/conformance/expressions/functionCalls/functionCalls.ts(34,1): error anyVar(undefined); ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2347: Untyped function calls may not accept type arguments. + ~~~~~~ +!!! error TS2304: Cannot find name 'Window'. // Invoke function call on value of a subtype of Function with no call signatures with no type arguments diff --git a/tests/baselines/reference/functionConstraintSatisfaction2.errors.txt b/tests/baselines/reference/functionConstraintSatisfaction2.errors.txt index 06cdca868ad..f87312634f8 100644 --- a/tests/baselines/reference/functionConstraintSatisfaction2.errors.txt +++ b/tests/baselines/reference/functionConstraintSatisfaction2.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'Function'. -tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(6,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(7,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(6,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(7,1): error TS2554: Expected 1 arguments, but got 2. tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(23,14): error TS2345: Argument of type 'Function' is not assignable to parameter of type '(x: string) => string'. Type 'Function' provides no match for the signature '(x: string): string'. tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(24,15): error TS2345: Argument of type '(x: string[]) => string[]' is not assignable to parameter of type '(x: string) => string'. @@ -36,10 +36,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstrain !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'Function'. foo(() => { }, 1); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. foo(1, () => { }); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. function foo2 string>(x: T): T { return x; } diff --git a/tests/baselines/reference/functionOverloads29.errors.txt b/tests/baselines/reference/functionOverloads29.errors.txt index 763405e351b..2423f53165f 100644 --- a/tests/baselines/reference/functionOverloads29.errors.txt +++ b/tests/baselines/reference/functionOverloads29.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionOverloads29.ts(4,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionOverloads29.ts(4,9): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionOverloads29.ts (1 errors) ==== @@ -7,5 +7,5 @@ tests/cases/compiler/functionOverloads29.ts(4,9): error TS2346: Supplied paramet function foo(bar:any):any{ return bar } var x = foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads34.errors.txt b/tests/baselines/reference/functionOverloads34.errors.txt index ccd771d2130..c47eabef592 100644 --- a/tests/baselines/reference/functionOverloads34.errors.txt +++ b/tests/baselines/reference/functionOverloads34.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionOverloads34.ts(4,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionOverloads34.ts(4,9): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionOverloads34.ts (1 errors) ==== @@ -7,5 +7,5 @@ tests/cases/compiler/functionOverloads34.ts(4,9): error TS2346: Supplied paramet function foo(bar:{a:any;}):any{ return bar } var x = foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads37.errors.txt b/tests/baselines/reference/functionOverloads37.errors.txt index 742e1bedb22..523c4912e80 100644 --- a/tests/baselines/reference/functionOverloads37.errors.txt +++ b/tests/baselines/reference/functionOverloads37.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionOverloads37.ts(4,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionOverloads37.ts(4,9): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionOverloads37.ts (1 errors) ==== @@ -7,5 +7,5 @@ tests/cases/compiler/functionOverloads37.ts(4,9): error TS2346: Supplied paramet function foo(bar:{a:any;}[]):any{ return bar } var x = foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt b/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt index aec6b9c34b7..7ff051bd63e 100644 --- a/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt +++ b/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt @@ -1,33 +1,33 @@ -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(2,14): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(2,14): error TS2558: Expected 0 type arguments, but got 1. tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(3,16): error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(4,14): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(8,15): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(9,15): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(4,14): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(8,15): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(9,15): error TS2558: Expected 0 type arguments, but got 1. tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(12,17): error TS2345: Argument of type 'U' is not assignable to parameter of type 'T'. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(13,15): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(14,15): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(13,15): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(14,15): error TS2558: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts (8 errors) ==== function foo(x:T, y:U, f: (v: T) => U) { var r1 = f(1); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var r2 = f(1); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. var r3 = f(null); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var r4 = f(null); var r11 = f(x); var r21 = f(x); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var r31 = f(null); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var r41 = f(null); var r12 = f(y); @@ -35,9 +35,9 @@ tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(14,15 !!! error TS2345: Argument of type 'U' is not assignable to parameter of type 'T'. var r22 = f(y); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var r32 = f(null); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var r42 = f(null); } \ No newline at end of file diff --git a/tests/baselines/reference/genericDefaultsErrors.errors.txt b/tests/baselines/reference/genericDefaultsErrors.errors.txt index 3d792f022ac..6200046c49f 100644 --- a/tests/baselines/reference/genericDefaultsErrors.errors.txt +++ b/tests/baselines/reference/genericDefaultsErrors.errors.txt @@ -3,8 +3,8 @@ tests/cases/compiler/genericDefaultsErrors.ts(4,59): error TS2344: Type 'T' does Type 'string' is not assignable to type 'number'. tests/cases/compiler/genericDefaultsErrors.ts(5,44): error TS2344: Type 'T' does not satisfy the constraint 'number'. tests/cases/compiler/genericDefaultsErrors.ts(6,39): error TS2344: Type 'number' does not satisfy the constraint 'T'. -tests/cases/compiler/genericDefaultsErrors.ts(10,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/genericDefaultsErrors.ts(13,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/genericDefaultsErrors.ts(10,1): error TS2558: Expected 2-3 type arguments, but got 1. +tests/cases/compiler/genericDefaultsErrors.ts(13,1): error TS2558: Expected 2-3 type arguments, but got 4. tests/cases/compiler/genericDefaultsErrors.ts(17,13): error TS2345: Argument of type '"a"' is not assignable to parameter of type 'number'. tests/cases/compiler/genericDefaultsErrors.ts(19,11): error TS2428: All declarations of 'i00' must have identical type parameters. tests/cases/compiler/genericDefaultsErrors.ts(20,11): error TS2428: All declarations of 'i00' must have identical type parameters. @@ -44,12 +44,12 @@ tests/cases/compiler/genericDefaultsErrors.ts(38,20): error TS4033: Property 'x' f11(); // ok f11<1>(); // error ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2-3 type arguments, but got 1. f11<1, 2>(); // ok f11<1, 2, 3>(); // ok f11<1, 2, 3, 4>(); // error ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2-3 type arguments, but got 4. declare function f12(a?: U): void; f12(); // ok diff --git a/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt b/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt index 5b9ed348583..d7dfc18d40f 100644 --- a/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt +++ b/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts(7,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts(7,1): error TS2554: Expected 1-3 arguments, but got 0. ==== tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts (1 errors) ==== @@ -10,7 +10,7 @@ tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts(7,1): error TS23 utils.fold(); // error ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-3 arguments, but got 0. utils.fold(null); // no error utils.fold(null, null); // no error utils.fold(null, null, null); // error: Unable to invoke type with no call signatures diff --git a/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt b/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt index ba9ec881f99..9f8694d2fca 100644 --- a/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt +++ b/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/genericWithOpenTypeParameters1.ts(7,40): error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. -tests/cases/compiler/genericWithOpenTypeParameters1.ts(8,35): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/genericWithOpenTypeParameters1.ts(9,35): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/genericWithOpenTypeParameters1.ts(8,35): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericWithOpenTypeParameters1.ts(9,35): error TS2558: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/genericWithOpenTypeParameters1.ts (3 errors) ==== @@ -15,9 +15,9 @@ tests/cases/compiler/genericWithOpenTypeParameters1.ts(9,35): error TS2346: Supp !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. var f2 = (x: B) => { return x.foo(1); } // error ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var f3 = (x: B) => { return x.foo(1); } // error ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var f4 = (x: B) => { return x.foo(1); } // no error \ No newline at end of file diff --git a/tests/baselines/reference/grammarAmbiguities.errors.txt b/tests/baselines/reference/grammarAmbiguities.errors.txt index 3d21f10de7b..d3d0637bd2c 100644 --- a/tests/baselines/reference/grammarAmbiguities.errors.txt +++ b/tests/baselines/reference/grammarAmbiguities.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(8,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(9,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(8,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(9,1): error TS2554: Expected 1 arguments, but got 2. ==== tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts (2 errors) ==== @@ -12,9 +12,9 @@ tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(9,1): er f(g(7)); f(g < A, B > 7); // Should error ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. f(g < A, B > +(7)); // Should error ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. \ No newline at end of file diff --git a/tests/baselines/reference/grammarAmbiguities1.errors.txt b/tests/baselines/reference/grammarAmbiguities1.errors.txt index 12df5f3c1e0..22467d7ee77 100644 --- a/tests/baselines/reference/grammarAmbiguities1.errors.txt +++ b/tests/baselines/reference/grammarAmbiguities1.errors.txt @@ -1,7 +1,7 @@ -tests/cases/compiler/grammarAmbiguities1.ts(8,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/grammarAmbiguities1.ts(8,1): error TS2554: Expected 1 arguments, but got 2. tests/cases/compiler/grammarAmbiguities1.ts(8,3): error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. tests/cases/compiler/grammarAmbiguities1.ts(8,10): error TS2365: Operator '>' cannot be applied to types 'typeof B' and 'number'. -tests/cases/compiler/grammarAmbiguities1.ts(9,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/grammarAmbiguities1.ts(9,1): error TS2554: Expected 1 arguments, but got 2. tests/cases/compiler/grammarAmbiguities1.ts(9,3): error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. tests/cases/compiler/grammarAmbiguities1.ts(9,10): error TS2365: Operator '>' cannot be applied to types 'typeof B' and 'number'. @@ -16,14 +16,14 @@ tests/cases/compiler/grammarAmbiguities1.ts(9,10): error TS2365: Operator '>' ca f(g(7)); f(g < A, B > 7); ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. ~~~~~ !!! error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. ~~~~~ !!! error TS2365: Operator '>' cannot be applied to types 'typeof B' and 'number'. f(g < A, B > +(7)); ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. ~~~~~ !!! error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. ~~~~~~~~ diff --git a/tests/baselines/reference/importDeclTypes.errors.txt b/tests/baselines/reference/importDeclTypes.errors.txt new file mode 100644 index 00000000000..ee2a9c86eb5 --- /dev/null +++ b/tests/baselines/reference/importDeclTypes.errors.txt @@ -0,0 +1,14 @@ +/a.ts(1,21): error TS6137: Cannot import type declaration files. Consider importing 'foo-bar' instead of '@types/foo-bar'. + + +==== /node_modules/@types/foo-bar/index.d.ts (0 errors) ==== + export interface Foo { + bar: string; + } + + // This should error +==== /a.ts (1 errors) ==== + import { Foo } from "@types/foo-bar"; + ~~~~~~~~~~~~~~~~ +!!! error TS6137: Cannot import type declaration files. Consider importing 'foo-bar' instead of '@types/foo-bar'. + \ No newline at end of file diff --git a/tests/baselines/reference/importDeclTypes.js b/tests/baselines/reference/importDeclTypes.js new file mode 100644 index 00000000000..640dd4a19b4 --- /dev/null +++ b/tests/baselines/reference/importDeclTypes.js @@ -0,0 +1,15 @@ +//// [tests/cases/compiler/importDeclTypes.ts] //// + +//// [index.d.ts] +export interface Foo { + bar: string; +} + +// This should error +//// [a.ts] +import { Foo } from "@types/foo-bar"; + + +//// [a.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.errors.txt b/tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.errors.txt new file mode 100644 index 00000000000..633b812c356 --- /dev/null +++ b/tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.errors.txt @@ -0,0 +1,27 @@ +tests/cases/compiler/main.ts(1,25): error TS2343: This syntax requires an imported helper named '__asyncGenerator', but module 'tslib' has no exported member '__asyncGenerator'. +tests/cases/compiler/main.ts(1,25): error TS2343: This syntax requires an imported helper named '__await', but module 'tslib' has no exported member '__await'. +tests/cases/compiler/main.ts(1,25): error TS2343: This syntax requires an imported helper named '__generator', but module 'tslib' has no exported member '__generator'. +tests/cases/compiler/main.ts(4,5): error TS2343: This syntax requires an imported helper named '__asyncDelegator', but module 'tslib' has no exported member '__asyncDelegator'. +tests/cases/compiler/main.ts(4,5): error TS2343: This syntax requires an imported helper named '__asyncValues', but module 'tslib' has no exported member '__asyncValues'. + + +==== tests/cases/compiler/main.ts (5 errors) ==== + export async function * f() { + ~ +!!! error TS2343: This syntax requires an imported helper named '__asyncGenerator', but module 'tslib' has no exported member '__asyncGenerator'. + ~ +!!! error TS2343: This syntax requires an imported helper named '__await', but module 'tslib' has no exported member '__await'. + ~ +!!! error TS2343: This syntax requires an imported helper named '__generator', but module 'tslib' has no exported member '__generator'. + await 1; + yield 2; + yield* [3]; + ~~~~~~~~~~ +!!! error TS2343: This syntax requires an imported helper named '__asyncDelegator', but module 'tslib' has no exported member '__asyncDelegator'. + ~~~~~~~~~~ +!!! error TS2343: This syntax requires an imported helper named '__asyncValues', but module 'tslib' has no exported member '__asyncValues'. + } + +==== tests/cases/compiler/tslib.d.ts (0 errors) ==== + export {} + \ No newline at end of file diff --git a/tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.js b/tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.js new file mode 100644 index 00000000000..699c4faf921 --- /dev/null +++ b/tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.js @@ -0,0 +1,37 @@ +//// [tests/cases/compiler/importHelpersNoHelpersForAsyncGenerators.ts] //// + +//// [main.ts] +export async function * f() { + await 1; + yield 2; + yield* [3]; +} + +//// [tslib.d.ts] +export {} + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var tslib_1 = require("tslib"); +function f() { + return tslib_1.__asyncGenerator(this, arguments, function f_1() { + return tslib_1.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, tslib_1.__await(1)]; + case 1: + _a.sent(); + return [4 /*yield*/, 2]; + case 2: + _a.sent(); + return [5 /*yield**/, tslib_1.__values(tslib_1.__asyncDelegator(tslib_1.__asyncValues([3])))]; + case 3: return [4 /*yield*/, tslib_1.__await.apply(void 0, [_a.sent()])]; + case 4: + _a.sent(); + return [2 /*return*/]; + } + }); + }); +} +exports.f = f; diff --git a/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt b/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt index 5162cd28fd5..05cc1ee1cd0 100644 --- a/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt +++ b/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(8,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(16,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(8,9): error TS2558: Expected 1 type arguments, but got 2. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(16,9): error TS2558: Expected 2 type arguments, but got 1. ==== tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts (2 errors) ==== @@ -12,7 +12,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGeneri var c = new C(); ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 1 type arguments, but got 2. class D { x: T @@ -22,4 +22,4 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGeneri // BUG 794238 var d = new D(); ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2558: Expected 2 type arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt b/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt index 8322fd3b2e4..196af18aa9a 100644 --- a/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt +++ b/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(8,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(11,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(8,9): error TS2558: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(11,9): error TS2350: Only a void function can be called with the 'new' keyword. -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(14,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(11,9): error TS2558: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(14,10): error TS2350: Only a void function can be called with the 'new' keyword. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(14,10): error TS2558: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(18,10): error TS2347: Untyped function calls may not accept type arguments. @@ -16,21 +16,21 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGen var c = new C(); ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. function Foo(): void { } var r = new Foo(); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. - ~~~~~~~~~~~~~~~~~ !!! error TS2350: Only a void function can be called with the 'new' keyword. + ~~~~~~~~~~~~~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. var f: { (): void }; var r2 = new f(); ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. - ~~~~~~~~~~~~~~~ !!! error TS2350: Only a void function can be called with the 'new' keyword. + ~~~~~~~~~~~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. var a: any; // BUG 790977 diff --git a/tests/baselines/reference/invalidTripleSlashReference.errors.txt b/tests/baselines/reference/invalidTripleSlashReference.errors.txt index 1de5ecaaae1..8fef26aa5aa 100644 --- a/tests/baselines/reference/invalidTripleSlashReference.errors.txt +++ b/tests/baselines/reference/invalidTripleSlashReference.errors.txt @@ -1,13 +1,13 @@ -tests/cases/compiler/invalidTripleSlashReference.ts(1,1): error TS6053: File 'tests/cases/compiler/filedoesnotexist.ts' not found. -tests/cases/compiler/invalidTripleSlashReference.ts(2,1): error TS6053: File 'tests/cases/compiler/otherdoesnotexist.d.ts' not found. +tests/cases/compiler/invalidTripleSlashReference.ts(1,22): error TS6053: File 'tests/cases/compiler/filedoesnotexist.ts' not found. +tests/cases/compiler/invalidTripleSlashReference.ts(2,22): error TS6053: File 'tests/cases/compiler/otherdoesnotexist.d.ts' not found. ==== tests/cases/compiler/invalidTripleSlashReference.ts (2 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/compiler/filedoesnotexist.ts' not found. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/compiler/otherdoesnotexist.d.ts' not found. // this test doesn't actually give the errors you want due to the way the compiler reports errors diff --git a/tests/baselines/reference/isolatedModulesDontElideReExportStar.js b/tests/baselines/reference/isolatedModulesDontElideReExportStar.js new file mode 100644 index 00000000000..4d546135f74 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesDontElideReExportStar.js @@ -0,0 +1,12 @@ +//// [tests/cases/compiler/isolatedModulesDontElideReExportStar.ts] //// + +//// [a.ts] +export type T = number; + +//// [b.ts] +export * from "./a"; + + +//// [a.js] +//// [b.js] +export * from "./a"; diff --git a/tests/baselines/reference/isolatedModulesDontElideReExportStar.symbols b/tests/baselines/reference/isolatedModulesDontElideReExportStar.symbols new file mode 100644 index 00000000000..38ab78bf498 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesDontElideReExportStar.symbols @@ -0,0 +1,8 @@ +=== /a.ts === +export type T = number; +>T : Symbol(T, Decl(a.ts, 0, 0)) + +=== /b.ts === +export * from "./a"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesDontElideReExportStar.types b/tests/baselines/reference/isolatedModulesDontElideReExportStar.types new file mode 100644 index 00000000000..4f68c5ded89 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesDontElideReExportStar.types @@ -0,0 +1,8 @@ +=== /a.ts === +export type T = number; +>T : number + +=== /b.ts === +export * from "./a"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesReExportType.errors.txt b/tests/baselines/reference/isolatedModulesReExportType.errors.txt new file mode 100644 index 00000000000..10c07cde084 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesReExportType.errors.txt @@ -0,0 +1,38 @@ +/user.ts(2,10): error TS1205: Cannot re-export a type when the '--isolatedModules' flag is provided. +/user.ts(17,10): error TS1205: Cannot re-export a type when the '--isolatedModules' flag is provided. + + +==== /user.ts (2 errors) ==== + // Error, can't re-export something that's only a type. + export { T } from "./exportT"; + ~ +!!! error TS1205: Cannot re-export a type when the '--isolatedModules' flag is provided. + export import T2 = require("./exportEqualsT"); + + // OK, has a value side + export { C } from "./exportValue"; + + // OK, even though the namespace it exports is only types. + import * as NS from "./exportT"; + export { NS }; + + // OK, syntactically clear that a type is being re-exported. + export type T3 = T; + + // Error, not clear (to an isolated module) whether `T4` is a type. + import { T } from "./exportT"; + export { T as T4 }; + ~~~~~~~ +!!! error TS1205: Cannot re-export a type when the '--isolatedModules' flag is provided. + +==== /exportT.ts (0 errors) ==== + export type T = number; + +==== /exportValue.ts (0 errors) ==== + export class C {} + +==== /exportEqualsT.ts (0 errors) ==== + declare type T = number; + export = T; + + \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesReExportType.js b/tests/baselines/reference/isolatedModulesReExportType.js new file mode 100644 index 00000000000..545e5a81a8a --- /dev/null +++ b/tests/baselines/reference/isolatedModulesReExportType.js @@ -0,0 +1,57 @@ +//// [tests/cases/compiler/isolatedModulesReExportType.ts] //// + +//// [exportT.ts] +export type T = number; + +//// [exportValue.ts] +export class C {} + +//// [exportEqualsT.ts] +declare type T = number; +export = T; + + +//// [user.ts] +// Error, can't re-export something that's only a type. +export { T } from "./exportT"; +export import T2 = require("./exportEqualsT"); + +// OK, has a value side +export { C } from "./exportValue"; + +// OK, even though the namespace it exports is only types. +import * as NS from "./exportT"; +export { NS }; + +// OK, syntactically clear that a type is being re-exported. +export type T3 = T; + +// Error, not clear (to an isolated module) whether `T4` is a type. +import { T } from "./exportT"; +export { T as T4 }; + + +//// [exportT.js] +"use strict"; +exports.__esModule = true; +//// [exportEqualsT.js] +"use strict"; +exports.__esModule = true; +//// [exportValue.js] +"use strict"; +exports.__esModule = true; +var C = (function () { + function C() { + } + return C; +}()); +exports.C = C; +//// [user.js] +"use strict"; +exports.__esModule = true; +// OK, has a value side +var exportValue_1 = require("./exportValue"); +exports.C = exportValue_1.C; +// OK, even though the namespace it exports is only types. +var NS = require("./exportT"); +exports.NS = NS; diff --git a/tests/baselines/reference/iteratorSpreadInCall.errors.txt b/tests/baselines/reference/iteratorSpreadInCall.errors.txt index d26f9ab6447..1831013b6e7 100644 --- a/tests/baselines/reference/iteratorSpreadInCall.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts(15,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts(15,1): error TS2556: Expected 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts(15,1): error TS2346: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2556: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall10.errors.txt b/tests/baselines/reference/iteratorSpreadInCall10.errors.txt index bf478012c5d..0d10c9f25e5 100644 --- a/tests/baselines/reference/iteratorSpreadInCall10.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall10.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts(15,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts(15,1): error TS2556: Expected 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts(15,1): error TS2346 foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2556: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall2.errors.txt b/tests/baselines/reference/iteratorSpreadInCall2.errors.txt index abf8fc71ed7..03cc296b8ab 100644 --- a/tests/baselines/reference/iteratorSpreadInCall2.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts(15,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts(15,1): error TS2556: Expected 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts(15,1): error TS2346: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2556: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall4.errors.txt b/tests/baselines/reference/iteratorSpreadInCall4.errors.txt index 3beaf2ce65c..899ac1d9e90 100644 --- a/tests/baselines/reference/iteratorSpreadInCall4.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts(15,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts(15,1): error TS2557: Expected at least 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts(15,1): error TS2346: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2557: Expected at least 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/jsDocTypeTag1.js b/tests/baselines/reference/jsDocTypeTag1.js new file mode 100644 index 00000000000..5dcabf2aa09 --- /dev/null +++ b/tests/baselines/reference/jsDocTypeTag1.js @@ -0,0 +1,584 @@ +[ + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 26 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 26, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "S", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "string", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 55 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 55, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "N", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 85 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 85, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "B", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "boolean", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 112 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 112, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "V", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "void", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 144 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 144, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "U", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "undefined", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 171 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 171, + "length": 2 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "Nl", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "null", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 200 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 200, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "A", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "any", + "kind": "keyword" + }, + { + "text": "[", + "kind": "punctuation" + }, + { + "text": "]", + "kind": "punctuation" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 230 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 230, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "P", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "Promise", + "kind": "interfaceName" + }, + { + "text": "<", + "kind": "punctuation" + }, + { + "text": "any", + "kind": "keyword" + }, + { + "text": ">", + "kind": "punctuation" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 259 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 259, + "length": 3 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "Obj", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "any", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 292 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 292, + "length": 4 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "Func", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "Function", + "kind": "localName" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 319 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 319, + "length": 7 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "AnyType", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "any", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 349 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 349, + "length": 5 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "QType", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "any", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 389 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 389, + "length": 4 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "SOrN", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "string", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "|", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + } +] \ No newline at end of file diff --git a/tests/baselines/reference/jsDocTypeTag2.js b/tests/baselines/reference/jsDocTypeTag2.js new file mode 100644 index 00000000000..07535dcee08 --- /dev/null +++ b/tests/baselines/reference/jsDocTypeTag2.js @@ -0,0 +1,598 @@ +[ + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 26 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 26, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "s", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "string", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 55 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 55, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "n", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 85 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 85, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "b", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "boolean", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 112 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 112, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "v", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "void", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 144 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 144, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "u", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "undefined", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 171 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 171, + "length": 2 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "nl", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "null", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 200 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 200, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "a", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "any", + "kind": "keyword" + }, + { + "text": "[", + "kind": "punctuation" + }, + { + "text": "]", + "kind": "punctuation" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 230 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 230, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "p", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "Promise", + "kind": "interfaceName" + }, + { + "text": "<", + "kind": "punctuation" + }, + { + "text": "any", + "kind": "keyword" + }, + { + "text": ">", + "kind": "punctuation" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 260 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 260, + "length": 8 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "nullable", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 298 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 298, + "length": 4 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "func", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "(", + "kind": "punctuation" + }, + { + "text": ")", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "=>", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "any", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 349 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 349, + "length": 5 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "func1", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "(", + "kind": "punctuation" + }, + { + "text": "arg0", + "kind": "parameterName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + }, + { + "text": ")", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "=>", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 391 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 391, + "length": 4 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "sOrn", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "string", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "|", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + } +] \ No newline at end of file diff --git a/tests/baselines/reference/jsDocTypes2.js b/tests/baselines/reference/jsDocTypes2.js new file mode 100644 index 00000000000..a3848704fad --- /dev/null +++ b/tests/baselines/reference/jsDocTypes2.js @@ -0,0 +1,37 @@ +//// [0.js] +// @ts-check +/** @type {*} */ +var anyT = 2; + +/** @type {?} */ +var anyT1 = 2; +anyT1 = "hi"; + +/** @type {Function} */ +const x = (a) => a + 1; +x(1); + +/** @type {function (number)} */ +const x1 = (a) => a + 1; +x1(0); + +/** @type {function (number): number} */ +const x2 = (a) => a + 1; +x2(0); + +//// [0.js] +// @ts-check +/** @type {*} */ +var anyT = 2; +/** @type {?} */ +var anyT1 = 2; +anyT1 = "hi"; +/** @type {Function} */ +var x = function (a) { return a + 1; }; +x(1); +/** @type {function (number)} */ +var x1 = function (a) { return a + 1; }; +x1(0); +/** @type {function (number): number} */ +var x2 = function (a) { return a + 1; }; +x2(0); diff --git a/tests/baselines/reference/jsDocTypes2.symbols b/tests/baselines/reference/jsDocTypes2.symbols new file mode 100644 index 00000000000..96b32b9ad91 --- /dev/null +++ b/tests/baselines/reference/jsDocTypes2.symbols @@ -0,0 +1,40 @@ +=== tests/cases/conformance/salsa/0.js === +// @ts-check +/** @type {*} */ +var anyT = 2; +>anyT : Symbol(anyT, Decl(0.js, 2, 3)) + +/** @type {?} */ +var anyT1 = 2; +>anyT1 : Symbol(anyT1, Decl(0.js, 5, 3)) + +anyT1 = "hi"; +>anyT1 : Symbol(anyT1, Decl(0.js, 5, 3)) + +/** @type {Function} */ +const x = (a) => a + 1; +>x : Symbol(x, Decl(0.js, 9, 5)) +>a : Symbol(a, Decl(0.js, 9, 11)) +>a : Symbol(a, Decl(0.js, 9, 11)) + +x(1); +>x : Symbol(x, Decl(0.js, 9, 5)) + +/** @type {function (number)} */ +const x1 = (a) => a + 1; +>x1 : Symbol(x1, Decl(0.js, 13, 5)) +>a : Symbol(a, Decl(0.js, 13, 12)) +>a : Symbol(a, Decl(0.js, 13, 12)) + +x1(0); +>x1 : Symbol(x1, Decl(0.js, 13, 5)) + +/** @type {function (number): number} */ +const x2 = (a) => a + 1; +>x2 : Symbol(x2, Decl(0.js, 17, 5)) +>a : Symbol(a, Decl(0.js, 17, 12)) +>a : Symbol(a, Decl(0.js, 17, 12)) + +x2(0); +>x2 : Symbol(x2, Decl(0.js, 17, 5)) + diff --git a/tests/baselines/reference/jsDocTypes2.types b/tests/baselines/reference/jsDocTypes2.types new file mode 100644 index 00000000000..db5a5902d10 --- /dev/null +++ b/tests/baselines/reference/jsDocTypes2.types @@ -0,0 +1,59 @@ +=== tests/cases/conformance/salsa/0.js === +// @ts-check +/** @type {*} */ +var anyT = 2; +>anyT : any +>2 : 2 + +/** @type {?} */ +var anyT1 = 2; +>anyT1 : any +>2 : 2 + +anyT1 = "hi"; +>anyT1 = "hi" : "hi" +>anyT1 : any +>"hi" : "hi" + +/** @type {Function} */ +const x = (a) => a + 1; +>x : Function +>(a) => a + 1 : (a: any) => any +>a : any +>a + 1 : any +>a : any +>1 : 1 + +x(1); +>x(1) : any +>x : Function +>1 : 1 + +/** @type {function (number)} */ +const x1 = (a) => a + 1; +>x1 : (arg0: number) => any +>(a) => a + 1 : (a: any) => any +>a : any +>a + 1 : any +>a : any +>1 : 1 + +x1(0); +>x1(0) : any +>x1 : (arg0: number) => any +>0 : 0 + +/** @type {function (number): number} */ +const x2 = (a) => a + 1; +>x2 : (arg0: number) => number +>(a) => a + 1 : (a: any) => any +>a : any +>a + 1 : any +>a : any +>1 : 1 + +x2(0); +>x2(0) : number +>x2 : (arg0: number) => number +>0 : 0 + diff --git a/tests/baselines/reference/jsDocTypes3.errors.txt b/tests/baselines/reference/jsDocTypes3.errors.txt new file mode 100644 index 00000000000..5f5feeaf0a7 --- /dev/null +++ b/tests/baselines/reference/jsDocTypes3.errors.txt @@ -0,0 +1,21 @@ +tests/cases/conformance/salsa/0.js(5,4): error TS2345: Argument of type '"string"' is not assignable to parameter of type 'number'. +tests/cases/conformance/salsa/0.js(12,1): error TS2322: Type 'number' is not assignable to type 'string'. + + +==== tests/cases/conformance/salsa/0.js (2 errors) ==== + // @ts-check + + /** @type {function (number)} */ + const x1 = (a) => a + 1; + x1("string"); + ~~~~~~~~ +!!! error TS2345: Argument of type '"string"' is not assignable to parameter of type 'number'. + + /** @type {function (number): number} */ + const x2 = (a) => a + 1; + + /** @type {string} */ + var a; + a = x2(0); + ~ +!!! error TS2322: Type 'number' is not assignable to type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/jsDocTypes3.js b/tests/baselines/reference/jsDocTypes3.js new file mode 100644 index 00000000000..2eb50223ba2 --- /dev/null +++ b/tests/baselines/reference/jsDocTypes3.js @@ -0,0 +1,24 @@ +//// [0.js] +// @ts-check + +/** @type {function (number)} */ +const x1 = (a) => a + 1; +x1("string"); + +/** @type {function (number): number} */ +const x2 = (a) => a + 1; + +/** @type {string} */ +var a; +a = x2(0); + +//// [0.js] +// @ts-check +/** @type {function (number)} */ +var x1 = function (a) { return a + 1; }; +x1("string"); +/** @type {function (number): number} */ +var x2 = function (a) { return a + 1; }; +/** @type {string} */ +var a; +a = x2(0); diff --git a/tests/baselines/reference/jsFileCompilationRestParamJsDocFunction.types b/tests/baselines/reference/jsFileCompilationRestParamJsDocFunction.types index 66e3da3e67f..54bc7938689 100644 --- a/tests/baselines/reference/jsFileCompilationRestParamJsDocFunction.types +++ b/tests/baselines/reference/jsFileCompilationRestParamJsDocFunction.types @@ -10,8 +10,8 @@ * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { ->apply : (func: {}, thisArg: any, ...args: any[]) => any ->func : {} +>apply : (func: Function, thisArg: any, ...args: any[]) => any +>func : Function >thisArg : any >args : any[] @@ -28,7 +28,7 @@ function apply(func, thisArg, args) { >0 : 0 >func.call(thisArg) : any >func.call : (this: Function, thisArg: any, ...argArray: any[]) => any ->func : {} +>func : Function >call : (this: Function, thisArg: any, ...argArray: any[]) => any >thisArg : any @@ -36,7 +36,7 @@ function apply(func, thisArg, args) { >1 : 1 >func.call(thisArg, args[0]) : any >func.call : (this: Function, thisArg: any, ...argArray: any[]) => any ->func : {} +>func : Function >call : (this: Function, thisArg: any, ...argArray: any[]) => any >thisArg : any >args[0] : any @@ -47,7 +47,7 @@ function apply(func, thisArg, args) { >2 : 2 >func.call(thisArg, args[0], args[1]) : any >func.call : (this: Function, thisArg: any, ...argArray: any[]) => any ->func : {} +>func : Function >call : (this: Function, thisArg: any, ...argArray: any[]) => any >thisArg : any >args[0] : any @@ -61,7 +61,7 @@ function apply(func, thisArg, args) { >3 : 3 >func.call(thisArg, args[0], args[1], args[2]) : any >func.call : (this: Function, thisArg: any, ...argArray: any[]) => any ->func : {} +>func : Function >call : (this: Function, thisArg: any, ...argArray: any[]) => any >thisArg : any >args[0] : any @@ -77,12 +77,12 @@ function apply(func, thisArg, args) { return func.apply(thisArg, args); >func.apply(thisArg, args) : any >func.apply : (this: Function, thisArg: any, argArray?: any) => any ->func : {} +>func : Function >apply : (this: Function, thisArg: any, argArray?: any) => any >thisArg : any >args : any[] } export default apply; ->apply : (func: {}, thisArg: any, ...args: any[]) => any +>apply : (func: Function, thisArg: any, ...args: any[]) => any diff --git a/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt b/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt index 236827b97bc..5a308a61b0f 100644 --- a/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt +++ b/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/bar.ts(1,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/bar.ts(2,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/bar.ts(3,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/bar.ts(1,1): error TS2554: Expected 3 arguments, but got 0. +tests/cases/compiler/bar.ts(2,1): error TS2554: Expected 3 arguments, but got 1. +tests/cases/compiler/bar.ts(3,1): error TS2554: Expected 3 arguments, but got 2. ==== tests/cases/compiler/foo.js (0 errors) ==== @@ -15,13 +15,13 @@ tests/cases/compiler/bar.ts(3,1): error TS2346: Supplied parameters do not match ==== tests/cases/compiler/bar.ts (3 errors) ==== f(); // Error ~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 3 arguments, but got 0. f(1); // Error ~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 3 arguments, but got 1. f(1, 2); // Error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 3 arguments, but got 2. f(1, 2, 3); // OK \ No newline at end of file diff --git a/tests/baselines/reference/jsdocInTypeScript.errors.txt b/tests/baselines/reference/jsdocInTypeScript.errors.txt new file mode 100644 index 00000000000..621aa4677b4 --- /dev/null +++ b/tests/baselines/reference/jsdocInTypeScript.errors.txt @@ -0,0 +1,49 @@ +tests/cases/compiler/jsdocInTypeScript.ts(16,23): error TS2304: Cannot find name 'MyType'. +tests/cases/compiler/jsdocInTypeScript.ts(23,33): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/jsdocInTypeScript.ts(25,3): error TS2345: Argument of type '1' is not assignable to parameter of type 'boolean'. +tests/cases/compiler/jsdocInTypeScript.ts(25,15): error TS2339: Property 'length' does not exist on type 'number'. +tests/cases/compiler/jsdocInTypeScript.ts(30,3): error TS2339: Property 'x' does not exist on type '{}'. + + +==== tests/cases/compiler/jsdocInTypeScript.ts (5 errors) ==== + // JSDoc typedef tags are not bound TypeScript files. + /** @typedef {function} T */ + declare const x: T; + + class T { + prop: number; + } + + x.prop; + + // Just to be sure that @property has no impact either. + /** + * @typedef {Object} MyType + * @property {string} yes + */ + declare const myType: MyType; // should error, no such type + ~~~~~~ +!!! error TS2304: Cannot find name 'MyType'. + + // @param type has no effect. + /** + * @param {number} x + * @returns string + */ + function f(x: boolean) { return x * 2; } // Should error + ~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + // Should fail, because it takes a boolean and returns a number + f(1); f(true).length; + ~ +!!! error TS2345: Argument of type '1' is not assignable to parameter of type 'boolean'. + ~~~~~~ +!!! error TS2339: Property 'length' does not exist on type 'number'. + + // @type has no effect either. + /** @type {{ x?: number }} */ + const z = {}; + z.x = 1; + ~ +!!! error TS2339: Property 'x' does not exist on type '{}'. + \ No newline at end of file diff --git a/tests/baselines/reference/jsdocInTypeScript.js b/tests/baselines/reference/jsdocInTypeScript.js index af4b8b6ce0a..29782e92592 100644 --- a/tests/baselines/reference/jsdocInTypeScript.js +++ b/tests/baselines/reference/jsdocInTypeScript.js @@ -8,6 +8,27 @@ class T { } x.prop; + +// Just to be sure that @property has no impact either. +/** + * @typedef {Object} MyType + * @property {string} yes + */ +declare const myType: MyType; // should error, no such type + +// @param type has no effect. +/** + * @param {number} x + * @returns string + */ +function f(x: boolean) { return x * 2; } // Should error +// Should fail, because it takes a boolean and returns a number +f(1); f(true).length; + +// @type has no effect either. +/** @type {{ x?: number }} */ +const z = {}; +z.x = 1; //// [jsdocInTypeScript.js] @@ -17,3 +38,16 @@ var T = (function () { return T; }()); x.prop; +// @param type has no effect. +/** + * @param {number} x + * @returns string + */ +function f(x) { return x * 2; } // Should error +// Should fail, because it takes a boolean and returns a number +f(1); +f(true).length; +// @type has no effect either. +/** @type {{ x?: number }} */ +var z = {}; +z.x = 1; diff --git a/tests/baselines/reference/jsdocInTypeScript.symbols b/tests/baselines/reference/jsdocInTypeScript.symbols deleted file mode 100644 index 62b6ad3c539..00000000000 --- a/tests/baselines/reference/jsdocInTypeScript.symbols +++ /dev/null @@ -1,19 +0,0 @@ -=== tests/cases/compiler/jsdocInTypeScript.ts === -// JSDoc typedef tags are not bound TypeScript files. -/** @typedef {function} T */ -declare const x: T; ->x : Symbol(x, Decl(jsdocInTypeScript.ts, 2, 13)) ->T : Symbol(T, Decl(jsdocInTypeScript.ts, 2, 19)) - -class T { ->T : Symbol(T, Decl(jsdocInTypeScript.ts, 2, 19)) - - prop: number; ->prop : Symbol(T.prop, Decl(jsdocInTypeScript.ts, 4, 9)) -} - -x.prop; ->x.prop : Symbol(T.prop, Decl(jsdocInTypeScript.ts, 4, 9)) ->x : Symbol(x, Decl(jsdocInTypeScript.ts, 2, 13)) ->prop : Symbol(T.prop, Decl(jsdocInTypeScript.ts, 4, 9)) - diff --git a/tests/baselines/reference/jsdocInTypeScript.types b/tests/baselines/reference/jsdocInTypeScript.types deleted file mode 100644 index 03ff2929e0a..00000000000 --- a/tests/baselines/reference/jsdocInTypeScript.types +++ /dev/null @@ -1,19 +0,0 @@ -=== tests/cases/compiler/jsdocInTypeScript.ts === -// JSDoc typedef tags are not bound TypeScript files. -/** @typedef {function} T */ -declare const x: T; ->x : T ->T : T - -class T { ->T : T - - prop: number; ->prop : number -} - -x.prop; ->x.prop : number ->x : T ->prop : number - diff --git a/tests/baselines/reference/letDeclarations-scopes2.errors.txt b/tests/baselines/reference/letDeclarations-scopes2.errors.txt index 8e0cf04aa14..5da8d99d397 100644 --- a/tests/baselines/reference/letDeclarations-scopes2.errors.txt +++ b/tests/baselines/reference/letDeclarations-scopes2.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/letDeclarations-scopes2.ts(8,5): error TS2304: Cannot find name 'local2'. -tests/cases/compiler/letDeclarations-scopes2.ts(20,5): error TS2304: Cannot find name 'local2'. +tests/cases/compiler/letDeclarations-scopes2.ts(8,5): error TS2552: Cannot find name 'local2'. Did you mean 'local'? +tests/cases/compiler/letDeclarations-scopes2.ts(20,5): error TS2552: Cannot find name 'local2'. Did you mean 'local'? tests/cases/compiler/letDeclarations-scopes2.ts(23,1): error TS2304: Cannot find name 'local'. tests/cases/compiler/letDeclarations-scopes2.ts(25,1): error TS2304: Cannot find name 'local2'. @@ -14,7 +14,7 @@ tests/cases/compiler/letDeclarations-scopes2.ts(25,1): error TS2304: Cannot find global; // OK local2; // Error ~~~~~~ -!!! error TS2304: Cannot find name 'local2'. +!!! error TS2552: Cannot find name 'local2'. Did you mean 'local'? { let local2 = 0; @@ -28,7 +28,7 @@ tests/cases/compiler/letDeclarations-scopes2.ts(25,1): error TS2304: Cannot find global; // OK local2; // Error ~~~~~~ -!!! error TS2304: Cannot find name 'local2'. +!!! error TS2552: Cannot find name 'local2'. Did you mean 'local'? } local; // Error diff --git a/tests/baselines/reference/library-reference-5.errors.txt b/tests/baselines/reference/library-reference-5.errors.txt index 2130b1ce037..173865ed82d 100644 --- a/tests/baselines/reference/library-reference-5.errors.txt +++ b/tests/baselines/reference/library-reference-5.errors.txt @@ -1,4 +1,4 @@ -/node_modules/bar/index.d.ts(1,1): message TS4090: Conflicting definitions for 'alpha' found at '/node_modules/bar/node_modules/alpha/index.d.ts' and '/node_modules/foo/node_modules/alpha/index.d.ts'. Consider installing a specific version of this library to resolve the conflict. +/node_modules/bar/index.d.ts(1,23): message TS4090: Conflicting definitions for 'alpha' found at '/node_modules/bar/node_modules/alpha/index.d.ts' and '/node_modules/foo/node_modules/alpha/index.d.ts'. Consider installing a specific version of this library to resolve the conflict. ==== /src/root.ts (0 errors) ==== @@ -16,7 +16,7 @@ ==== /node_modules/bar/index.d.ts (1 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~ !!! message TS4090: Conflicting definitions for 'alpha' found at '/node_modules/bar/node_modules/alpha/index.d.ts' and '/node_modules/foo/node_modules/alpha/index.d.ts'. Consider installing a specific version of this library to resolve the conflict. declare var bar: any; diff --git a/tests/baselines/reference/literalTypes2.types b/tests/baselines/reference/literalTypes2.types index 716b016f64e..ab1d3e199d2 100644 --- a/tests/baselines/reference/literalTypes2.types +++ b/tests/baselines/reference/literalTypes2.types @@ -290,7 +290,7 @@ function f3() { >c2 : 1 | "two" let x3 = c3; ->x3 : number | boolean | E +>x3 : number | boolean >c3 : true | E.A | 123 let x4 = c4; diff --git a/tests/baselines/reference/logicalAndOperatorWithEveryType.types b/tests/baselines/reference/logicalAndOperatorWithEveryType.types index 54770acfab4..cbe37d54a4f 100644 --- a/tests/baselines/reference/logicalAndOperatorWithEveryType.types +++ b/tests/baselines/reference/logicalAndOperatorWithEveryType.types @@ -365,7 +365,7 @@ var rf5 = a5 && a6; var rf6 = a6 && a6; >rf6 : E ->a6 && a6 : E.b | E.c +>a6 && a6 : E >a6 : E >a6 : E.b | E.c diff --git a/tests/baselines/reference/logicalOrOperatorWithEveryType.types b/tests/baselines/reference/logicalOrOperatorWithEveryType.types index 327ae64cf07..5e6fa98d749 100644 --- a/tests/baselines/reference/logicalOrOperatorWithEveryType.types +++ b/tests/baselines/reference/logicalOrOperatorWithEveryType.types @@ -128,7 +128,7 @@ var rb5 = a5 || a2; // void || boolean is void | boolean var rb6 = a6 || a2; // enum || boolean is E | boolean >rb6 : boolean | E ->a6 || a2 : boolean | E +>a6 || a2 : boolean | E.b | E.c >a6 : E >a2 : boolean @@ -248,7 +248,7 @@ var rd5 = a5 || a4; // void || string is void | string var rd6 = a6 || a4; // enum || string is enum | string >rd6 : string | E ->a6 || a4 : string | E +>a6 || a4 : string | E.b | E.c >a6 : E >a4 : string @@ -308,7 +308,7 @@ var re5 = a5 || a5; // void || void is void var re6 = a6 || a5; // enum || void is enum | void >re6 : void | E ->a6 || a5 : void | E +>a6 || a5 : void | E.b | E.c >a6 : E >a5 : void @@ -428,7 +428,7 @@ var rh5 = a5 || a7; // void || object is void | object var rh6 = a6 || a7; // enum || object is enum | object >rh6 : E | { a: string; } ->a6 || a7 : E | { a: string; } +>a6 || a7 : E.b | E.c | { a: string; } >a6 : E >a7 : { a: string; } @@ -488,7 +488,7 @@ var ri5 = a5 || a8; // void || array is void | array var ri6 = a6 || a8; // enum || array is enum | array >ri6 : E | string[] ->a6 || a8 : E | string[] +>a6 || a8 : E.b | E.c | string[] >a6 : E >a8 : string[] @@ -548,7 +548,7 @@ var rj5 = a5 || null; // void || null is void var rj6 = a6 || null; // enum || null is E >rj6 : E ->a6 || null : E +>a6 || null : E.b | E.c >a6 : E >null : null @@ -608,7 +608,7 @@ var rf5 = a5 || undefined; // void || undefined is void var rf6 = a6 || undefined; // enum || undefined is E >rf6 : E ->a6 || undefined : E +>a6 || undefined : E.b | E.c >a6 : E >undefined : undefined diff --git a/tests/baselines/reference/maximum10SpellingSuggestions.errors.txt b/tests/baselines/reference/maximum10SpellingSuggestions.errors.txt new file mode 100644 index 00000000000..8069d7bd1f5 --- /dev/null +++ b/tests/baselines/reference/maximum10SpellingSuggestions.errors.txt @@ -0,0 +1,45 @@ +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,1): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,6): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,11): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,16): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,21): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,26): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,31): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,36): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,41): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,46): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(5,1): error TS2304: Cannot find name 'bob'. +tests/cases/compiler/maximum10SpellingSuggestions.ts(5,6): error TS2304: Cannot find name 'bob'. + + +==== tests/cases/compiler/maximum10SpellingSuggestions.ts (12 errors) ==== + // 10 bobs on the first line + // the last two bobs should not have did-you-mean spelling suggestions + var blob; + bob; bob; bob; bob; bob; bob; bob; bob; bob; bob; + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + bob; bob; + ~~~ +!!! error TS2304: Cannot find name 'bob'. + ~~~ +!!! error TS2304: Cannot find name 'bob'. + \ No newline at end of file diff --git a/tests/baselines/reference/maximum10SpellingSuggestions.js b/tests/baselines/reference/maximum10SpellingSuggestions.js new file mode 100644 index 00000000000..eedd55b0840 --- /dev/null +++ b/tests/baselines/reference/maximum10SpellingSuggestions.js @@ -0,0 +1,24 @@ +//// [maximum10SpellingSuggestions.ts] +// 10 bobs on the first line +// the last two bobs should not have did-you-mean spelling suggestions +var blob; +bob; bob; bob; bob; bob; bob; bob; bob; bob; bob; +bob; bob; + + +//// [maximum10SpellingSuggestions.js] +// 10 bobs on the first line +// the last two bobs should not have did-you-mean spelling suggestions +var blob; +bob; +bob; +bob; +bob; +bob; +bob; +bob; +bob; +bob; +bob; +bob; +bob; diff --git a/tests/baselines/reference/metadataOfClassFromAlias.js b/tests/baselines/reference/metadataOfClassFromAlias.js new file mode 100644 index 00000000000..c99f7cc2e23 --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromAlias.js @@ -0,0 +1,50 @@ +//// [tests/cases/compiler/metadataOfClassFromAlias.ts] //// + +//// [auxiliry.ts] +export class SomeClass { + field: string; +} + +//// [test.ts] +import { SomeClass } from './auxiliry'; +function annotation(): PropertyDecorator { + return (target: any): void => { }; +} +export class ClassA { + @annotation() array: SomeClass | null; +} + +//// [auxiliry.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var SomeClass = (function () { + function SomeClass() { + } + return SomeClass; +}()); +exports.SomeClass = SomeClass; +//// [test.js] +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +function annotation() { + return function (target) { }; +} +var ClassA = (function () { + function ClassA() { + } + return ClassA; +}()); +__decorate([ + annotation(), + __metadata("design:type", Object) +], ClassA.prototype, "array", void 0); +exports.ClassA = ClassA; diff --git a/tests/baselines/reference/metadataOfClassFromAlias.symbols b/tests/baselines/reference/metadataOfClassFromAlias.symbols new file mode 100644 index 00000000000..b4d20403275 --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromAlias.symbols @@ -0,0 +1,27 @@ +=== tests/cases/compiler/auxiliry.ts === +export class SomeClass { +>SomeClass : Symbol(SomeClass, Decl(auxiliry.ts, 0, 0)) + + field: string; +>field : Symbol(SomeClass.field, Decl(auxiliry.ts, 0, 24)) +} + +=== tests/cases/compiler/test.ts === +import { SomeClass } from './auxiliry'; +>SomeClass : Symbol(SomeClass, Decl(test.ts, 0, 8)) + +function annotation(): PropertyDecorator { +>annotation : Symbol(annotation, Decl(test.ts, 0, 39)) +>PropertyDecorator : Symbol(PropertyDecorator, Decl(lib.d.ts, --, --)) + + return (target: any): void => { }; +>target : Symbol(target, Decl(test.ts, 2, 12)) +} +export class ClassA { +>ClassA : Symbol(ClassA, Decl(test.ts, 3, 1)) + + @annotation() array: SomeClass | null; +>annotation : Symbol(annotation, Decl(test.ts, 0, 39)) +>array : Symbol(ClassA.array, Decl(test.ts, 4, 21)) +>SomeClass : Symbol(SomeClass, Decl(test.ts, 0, 8)) +} diff --git a/tests/baselines/reference/metadataOfClassFromAlias.types b/tests/baselines/reference/metadataOfClassFromAlias.types new file mode 100644 index 00000000000..a14f72ee619 --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromAlias.types @@ -0,0 +1,30 @@ +=== tests/cases/compiler/auxiliry.ts === +export class SomeClass { +>SomeClass : SomeClass + + field: string; +>field : string +} + +=== tests/cases/compiler/test.ts === +import { SomeClass } from './auxiliry'; +>SomeClass : typeof SomeClass + +function annotation(): PropertyDecorator { +>annotation : () => PropertyDecorator +>PropertyDecorator : PropertyDecorator + + return (target: any): void => { }; +>(target: any): void => { } : (target: any) => void +>target : any +} +export class ClassA { +>ClassA : ClassA + + @annotation() array: SomeClass | null; +>annotation() : PropertyDecorator +>annotation : () => PropertyDecorator +>array : SomeClass +>SomeClass : SomeClass +>null : null +} diff --git a/tests/baselines/reference/metadataOfClassFromAlias2.js b/tests/baselines/reference/metadataOfClassFromAlias2.js new file mode 100644 index 00000000000..bcdbb34ac50 --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromAlias2.js @@ -0,0 +1,50 @@ +//// [tests/cases/compiler/metadataOfClassFromAlias2.ts] //// + +//// [auxiliry.ts] +export class SomeClass { + field: string; +} + +//// [test.ts] +import { SomeClass } from './auxiliry'; +function annotation(): PropertyDecorator { + return (target: any): void => { }; +} +export class ClassA { + @annotation() array: SomeClass | null | string; +} + +//// [auxiliry.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var SomeClass = (function () { + function SomeClass() { + } + return SomeClass; +}()); +exports.SomeClass = SomeClass; +//// [test.js] +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +function annotation() { + return function (target) { }; +} +var ClassA = (function () { + function ClassA() { + } + return ClassA; +}()); +__decorate([ + annotation(), + __metadata("design:type", Object) +], ClassA.prototype, "array", void 0); +exports.ClassA = ClassA; diff --git a/tests/baselines/reference/metadataOfClassFromAlias2.symbols b/tests/baselines/reference/metadataOfClassFromAlias2.symbols new file mode 100644 index 00000000000..a20296c76af --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromAlias2.symbols @@ -0,0 +1,27 @@ +=== tests/cases/compiler/auxiliry.ts === +export class SomeClass { +>SomeClass : Symbol(SomeClass, Decl(auxiliry.ts, 0, 0)) + + field: string; +>field : Symbol(SomeClass.field, Decl(auxiliry.ts, 0, 24)) +} + +=== tests/cases/compiler/test.ts === +import { SomeClass } from './auxiliry'; +>SomeClass : Symbol(SomeClass, Decl(test.ts, 0, 8)) + +function annotation(): PropertyDecorator { +>annotation : Symbol(annotation, Decl(test.ts, 0, 39)) +>PropertyDecorator : Symbol(PropertyDecorator, Decl(lib.d.ts, --, --)) + + return (target: any): void => { }; +>target : Symbol(target, Decl(test.ts, 2, 12)) +} +export class ClassA { +>ClassA : Symbol(ClassA, Decl(test.ts, 3, 1)) + + @annotation() array: SomeClass | null | string; +>annotation : Symbol(annotation, Decl(test.ts, 0, 39)) +>array : Symbol(ClassA.array, Decl(test.ts, 4, 21)) +>SomeClass : Symbol(SomeClass, Decl(test.ts, 0, 8)) +} diff --git a/tests/baselines/reference/metadataOfClassFromAlias2.types b/tests/baselines/reference/metadataOfClassFromAlias2.types new file mode 100644 index 00000000000..20979a5c77d --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromAlias2.types @@ -0,0 +1,30 @@ +=== tests/cases/compiler/auxiliry.ts === +export class SomeClass { +>SomeClass : SomeClass + + field: string; +>field : string +} + +=== tests/cases/compiler/test.ts === +import { SomeClass } from './auxiliry'; +>SomeClass : typeof SomeClass + +function annotation(): PropertyDecorator { +>annotation : () => PropertyDecorator +>PropertyDecorator : PropertyDecorator + + return (target: any): void => { }; +>(target: any): void => { } : (target: any) => void +>target : any +} +export class ClassA { +>ClassA : ClassA + + @annotation() array: SomeClass | null | string; +>annotation() : PropertyDecorator +>annotation : () => PropertyDecorator +>array : string | SomeClass +>SomeClass : SomeClass +>null : null +} diff --git a/tests/baselines/reference/metadataOfUnion.types b/tests/baselines/reference/metadataOfUnion.types index 08afc4e81bb..542d37e2085 100644 --- a/tests/baselines/reference/metadataOfUnion.types +++ b/tests/baselines/reference/metadataOfUnion.types @@ -81,6 +81,6 @@ class D { >PropDeco : (target: Object, propKey: string | symbol) => void d: E | number; ->d : number | E +>d : number >E : E } diff --git a/tests/baselines/reference/metadataOfUnionWithNull.js b/tests/baselines/reference/metadataOfUnionWithNull.js index cc594ae326d..0c834be9687 100644 --- a/tests/baselines/reference/metadataOfUnionWithNull.js +++ b/tests/baselines/reference/metadataOfUnionWithNull.js @@ -65,15 +65,15 @@ var B = (function () { }()); __decorate([ PropDeco, - __metadata("design:type", String) + __metadata("design:type", Object) ], B.prototype, "x"); __decorate([ PropDeco, - __metadata("design:type", Boolean) + __metadata("design:type", Object) ], B.prototype, "y"); __decorate([ PropDeco, - __metadata("design:type", String) + __metadata("design:type", Object) ], B.prototype, "z"); __decorate([ PropDeco, @@ -89,11 +89,11 @@ __decorate([ ], B.prototype, "c"); __decorate([ PropDeco, - __metadata("design:type", void 0) + __metadata("design:type", Object) ], B.prototype, "d"); __decorate([ PropDeco, - __metadata("design:type", typeof Symbol === "function" ? Symbol : Object) + __metadata("design:type", Object) ], B.prototype, "e"); __decorate([ PropDeco, @@ -101,13 +101,13 @@ __decorate([ ], B.prototype, "f"); __decorate([ PropDeco, - __metadata("design:type", A) + __metadata("design:type", Object) ], B.prototype, "g"); __decorate([ PropDeco, - __metadata("design:type", B) + __metadata("design:type", Object) ], B.prototype, "h"); __decorate([ PropDeco, - __metadata("design:type", typeof Symbol === "function" ? Symbol : Object) + __metadata("design:type", Object) ], B.prototype, "j"); diff --git a/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt b/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt index 2fb7bd1bfbb..9b95b143d64 100644 --- a/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt +++ b/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(10,30): error TS2345: Argument of type '(string | number)[]' is not assignable to parameter of type 'number[]'. Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(11,11): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(11,11): error TS2558: Expected 2 type arguments, but got 1. ==== tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts (2 errors) ==== @@ -21,5 +21,5 @@ tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(11,11): e !!! error TS2345: Type 'string' is not assignable to type 'number'. var r7b = map([1, ""], (x) => x.toString()); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 2 type arguments, but got 1. var r8 = map([1, ""], (x) => x.toString()); \ No newline at end of file diff --git a/tests/baselines/reference/mixinAccessModifiers.errors.txt b/tests/baselines/reference/mixinAccessModifiers.errors.txt index a93725e01d2..fa2fc4ac99a 100644 --- a/tests/baselines/reference/mixinAccessModifiers.errors.txt +++ b/tests/baselines/reference/mixinAccessModifiers.errors.txt @@ -5,25 +5,19 @@ tests/cases/conformance/classes/mixinAccessModifiers.ts(50,4): error TS2445: Pro tests/cases/conformance/classes/mixinAccessModifiers.ts(65,7): error TS2415: Class 'C1' incorrectly extends base class 'Private & Private2'. Type 'C1' is not assignable to type 'Private'. Property 'p' has conflicting declarations and is inaccessible in type 'C1'. -tests/cases/conformance/classes/mixinAccessModifiers.ts(65,7): error TS4093: 'extends' clause of exported class 'C1' refers to a type whose name cannot be referenced. tests/cases/conformance/classes/mixinAccessModifiers.ts(66,7): error TS2415: Class 'C2' incorrectly extends base class 'Private & Protected'. Type 'C2' is not assignable to type 'Private'. Property 'p' has conflicting declarations and is inaccessible in type 'C2'. -tests/cases/conformance/classes/mixinAccessModifiers.ts(66,7): error TS4093: 'extends' clause of exported class 'C2' refers to a type whose name cannot be referenced. tests/cases/conformance/classes/mixinAccessModifiers.ts(67,7): error TS2415: Class 'C3' incorrectly extends base class 'Private & Public'. Type 'C3' is not assignable to type 'Private'. Property 'p' has conflicting declarations and is inaccessible in type 'C3'. -tests/cases/conformance/classes/mixinAccessModifiers.ts(67,7): error TS4093: 'extends' clause of exported class 'C3' refers to a type whose name cannot be referenced. -tests/cases/conformance/classes/mixinAccessModifiers.ts(69,7): error TS4093: 'extends' clause of exported class 'C4' refers to a type whose name cannot be referenced. -tests/cases/conformance/classes/mixinAccessModifiers.ts(82,7): error TS4093: 'extends' clause of exported class 'C5' refers to a type whose name cannot be referenced. tests/cases/conformance/classes/mixinAccessModifiers.ts(84,6): error TS2445: Property 'p' is protected and only accessible within class 'C4' and its subclasses. tests/cases/conformance/classes/mixinAccessModifiers.ts(89,6): error TS2445: Property 's' is protected and only accessible within class 'typeof C4' and its subclasses. -tests/cases/conformance/classes/mixinAccessModifiers.ts(95,7): error TS4093: 'extends' clause of exported class 'C6' refers to a type whose name cannot be referenced. tests/cases/conformance/classes/mixinAccessModifiers.ts(97,6): error TS2445: Property 'p' is protected and only accessible within class 'C4' and its subclasses. tests/cases/conformance/classes/mixinAccessModifiers.ts(102,6): error TS2445: Property 's' is protected and only accessible within class 'typeof C4' and its subclasses. -==== tests/cases/conformance/classes/mixinAccessModifiers.ts (17 errors) ==== +==== tests/cases/conformance/classes/mixinAccessModifiers.ts (11 errors) ==== type Constructable = new (...args: any[]) => object; class Private { @@ -101,26 +95,18 @@ tests/cases/conformance/classes/mixinAccessModifiers.ts(102,6): error TS2445: Pr !!! error TS2415: Class 'C1' incorrectly extends base class 'Private & Private2'. !!! error TS2415: Type 'C1' is not assignable to type 'Private'. !!! error TS2415: Property 'p' has conflicting declarations and is inaccessible in type 'C1'. - ~~ -!!! error TS4093: 'extends' clause of exported class 'C1' refers to a type whose name cannot be referenced. class C2 extends Mix(Private, Protected) {} ~~ !!! error TS2415: Class 'C2' incorrectly extends base class 'Private & Protected'. !!! error TS2415: Type 'C2' is not assignable to type 'Private'. !!! error TS2415: Property 'p' has conflicting declarations and is inaccessible in type 'C2'. - ~~ -!!! error TS4093: 'extends' clause of exported class 'C2' refers to a type whose name cannot be referenced. class C3 extends Mix(Private, Public) {} ~~ !!! error TS2415: Class 'C3' incorrectly extends base class 'Private & Public'. !!! error TS2415: Type 'C3' is not assignable to type 'Private'. !!! error TS2415: Property 'p' has conflicting declarations and is inaccessible in type 'C3'. - ~~ -!!! error TS4093: 'extends' clause of exported class 'C3' refers to a type whose name cannot be referenced. class C4 extends Mix(Protected, Protected2) { - ~~ -!!! error TS4093: 'extends' clause of exported class 'C4' refers to a type whose name cannot be referenced. f(c4: C4, c5: C5, c6: C6) { c4.p; c5.p; @@ -134,8 +120,6 @@ tests/cases/conformance/classes/mixinAccessModifiers.ts(102,6): error TS2445: Pr } class C5 extends Mix(Protected, Public) { - ~~ -!!! error TS4093: 'extends' clause of exported class 'C5' refers to a type whose name cannot be referenced. f(c4: C4, c5: C5, c6: C6) { c4.p; // Error, not in class deriving from Protected2 ~ @@ -153,8 +137,6 @@ tests/cases/conformance/classes/mixinAccessModifiers.ts(102,6): error TS2445: Pr } class C6 extends Mix(Public, Public2) { - ~~ -!!! error TS4093: 'extends' clause of exported class 'C6' refers to a type whose name cannot be referenced. f(c4: C4, c5: C5, c6: C6) { c4.p; // Error, not in class deriving from Protected2 ~ diff --git a/tests/baselines/reference/mixinAccessModifiers.js b/tests/baselines/reference/mixinAccessModifiers.js index 8100c9db9e9..736808455bb 100644 --- a/tests/baselines/reference/mixinAccessModifiers.js +++ b/tests/baselines/reference/mixinAccessModifiers.js @@ -263,3 +263,66 @@ var C6 = (function (_super) { }; return C6; }(Mix(Public, Public2))); + + +//// [mixinAccessModifiers.d.ts] +declare type Constructable = new (...args: any[]) => object; +declare class Private { + constructor(...args: any[]); + private p; +} +declare class Private2 { + constructor(...args: any[]); + private p; +} +declare class Protected { + constructor(...args: any[]); + protected p: string; + protected static s: string; +} +declare class Protected2 { + constructor(...args: any[]); + protected p: string; + protected static s: string; +} +declare class Public { + constructor(...args: any[]); + p: string; + static s: string; +} +declare class Public2 { + constructor(...args: any[]); + p: string; + static s: string; +} +declare function f1(x: Private & Private2): void; +declare function f2(x: Private & Protected): void; +declare function f3(x: Private & Public): void; +declare function f4(x: Protected & Protected2): void; +declare function f5(x: Protected & Public): void; +declare function f6(x: Public & Public2): void; +declare function Mix(c1: T, c2: U): T & U; +declare const C1_base: typeof Private & typeof Private2; +declare class C1 extends C1_base { +} +declare const C2_base: typeof Private & typeof Protected; +declare class C2 extends C2_base { +} +declare const C3_base: typeof Private & typeof Public; +declare class C3 extends C3_base { +} +declare const C4_base: typeof Protected & typeof Protected2; +declare class C4 extends C4_base { + f(c4: C4, c5: C5, c6: C6): void; + static g(): void; +} +declare const C5_base: typeof Protected & typeof Public; +declare class C5 extends C5_base { + f(c4: C4, c5: C5, c6: C6): void; + static g(): void; +} +declare const C6_base: typeof Public & typeof Public2; +declare class C6 extends C6_base { + f(c4: C4, c5: C5, c6: C6): void; + static g(): void; +} diff --git a/tests/baselines/reference/modularizeLibrary_Dom.iterable.types b/tests/baselines/reference/modularizeLibrary_Dom.iterable.types index e8656beb985..b06aaa08297 100644 --- a/tests/baselines/reference/modularizeLibrary_Dom.iterable.types +++ b/tests/baselines/reference/modularizeLibrary_Dom.iterable.types @@ -2,9 +2,9 @@ for (const element of document.getElementsByTagName("a")) { >element : HTMLAnchorElement >document.getElementsByTagName("a") : NodeListOf ->document.getElementsByTagName : { (tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf; } +>document.getElementsByTagName : { (tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf; } >document : Document ->getElementsByTagName : { (tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf; } +>getElementsByTagName : { (tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf; } >"a" : "a" element.href; diff --git a/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt b/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt index 80b8e345cde..b56b03de533 100644 --- a/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt +++ b/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(4,18): error TS2339: Property 'from' does not exist on type 'ArrayConstructor'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(10,13): error TS2304: Cannot find name 'Map'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(17,5): error TS2339: Property 'name' does not exist on type '() => void'. -tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(20,6): error TS2339: Property 'sign' does not exist on type 'Math'. +tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(20,6): error TS2551: Property 'sign' does not exist on type 'Math'. Did you mean 'sin'? tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(25,6): error TS2304: Cannot find name 'Symbol'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(29,18): error TS2304: Cannot find name 'Symbol'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(33,13): error TS2304: Cannot find name 'Proxy'. @@ -40,7 +40,7 @@ tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.t // Using ES6 math Math.sign(1); ~~~~ -!!! error TS2339: Property 'sign' does not exist on type 'Math'. +!!! error TS2551: Property 'sign' does not exist on type 'Math'. Did you mean 'sin'? // Using ES6 object var o = { diff --git a/tests/baselines/reference/narrowExceptionVariableInCatchClause.errors.txt b/tests/baselines/reference/narrowExceptionVariableInCatchClause.errors.txt index e435b98050d..248d4c35473 100644 --- a/tests/baselines/reference/narrowExceptionVariableInCatchClause.errors.txt +++ b/tests/baselines/reference/narrowExceptionVariableInCatchClause.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/types/any/narrowExceptionVariableInCatchClause.ts(11,17): error TS2339: Property 'doPanic' does not exist on type '{ type: "foo"; dontPanic(): any; }'. -tests/cases/conformance/types/any/narrowExceptionVariableInCatchClause.ts(16,17): error TS2339: Property 'massage' does not exist on type 'Error'. +tests/cases/conformance/types/any/narrowExceptionVariableInCatchClause.ts(11,17): error TS2551: Property 'doPanic' does not exist on type '{ type: "foo"; dontPanic(): any; }'. Did you mean 'dontPanic'? +tests/cases/conformance/types/any/narrowExceptionVariableInCatchClause.ts(16,17): error TS2551: Property 'massage' does not exist on type 'Error'. Did you mean 'message'? ==== tests/cases/conformance/types/any/narrowExceptionVariableInCatchClause.ts (2 errors) ==== @@ -15,14 +15,14 @@ tests/cases/conformance/types/any/narrowExceptionVariableInCatchClause.ts(16,17) err.dontPanic(); // OK err.doPanic(); // ERROR: Property 'doPanic' does not exist on type '{...}' ~~~~~~~ -!!! error TS2339: Property 'doPanic' does not exist on type '{ type: "foo"; dontPanic(): any; }'. +!!! error TS2551: Property 'doPanic' does not exist on type '{ type: "foo"; dontPanic(): any; }'. Did you mean 'dontPanic'? } else if (err instanceof Error) { err.message; err.massage; // ERROR: Property 'massage' does not exist on type 'Error' ~~~~~~~ -!!! error TS2339: Property 'massage' does not exist on type 'Error'. +!!! error TS2551: Property 'massage' does not exist on type 'Error'. Did you mean 'message'? } else { diff --git a/tests/baselines/reference/narrowFromAnyWithInstanceof.errors.txt b/tests/baselines/reference/narrowFromAnyWithInstanceof.errors.txt index 3e152b0faf4..f8465651901 100644 --- a/tests/baselines/reference/narrowFromAnyWithInstanceof.errors.txt +++ b/tests/baselines/reference/narrowFromAnyWithInstanceof.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/types/any/narrowFromAnyWithInstanceof.ts(17,7): error TS2339: Property 'mesage' does not exist on type 'Error'. -tests/cases/conformance/types/any/narrowFromAnyWithInstanceof.ts(22,7): error TS2339: Property 'getHuors' does not exist on type 'Date'. +tests/cases/conformance/types/any/narrowFromAnyWithInstanceof.ts(17,7): error TS2551: Property 'mesage' does not exist on type 'Error'. Did you mean 'message'? +tests/cases/conformance/types/any/narrowFromAnyWithInstanceof.ts(22,7): error TS2551: Property 'getHuors' does not exist on type 'Date'. Did you mean 'getHours'? ==== tests/cases/conformance/types/any/narrowFromAnyWithInstanceof.ts (2 errors) ==== @@ -21,13 +21,13 @@ tests/cases/conformance/types/any/narrowFromAnyWithInstanceof.ts(22,7): error TS x.message; x.mesage; ~~~~~~ -!!! error TS2339: Property 'mesage' does not exist on type 'Error'. +!!! error TS2551: Property 'mesage' does not exist on type 'Error'. Did you mean 'message'? } if (x instanceof Date) { x.getDate(); x.getHuors(); ~~~~~~~~ -!!! error TS2339: Property 'getHuors' does not exist on type 'Date'. +!!! error TS2551: Property 'getHuors' does not exist on type 'Date'. Did you mean 'getHours'? } \ No newline at end of file diff --git a/tests/baselines/reference/narrowFromAnyWithTypePredicate.errors.txt b/tests/baselines/reference/narrowFromAnyWithTypePredicate.errors.txt index c06c8a98801..4865748f332 100644 --- a/tests/baselines/reference/narrowFromAnyWithTypePredicate.errors.txt +++ b/tests/baselines/reference/narrowFromAnyWithTypePredicate.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(22,7): error TS2339: Property 'method' does not exist on type '{}'. tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(23,5): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '{}' has no compatible call signatures. -tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(28,7): error TS2339: Property 'mesage' does not exist on type 'Error'. -tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(33,7): error TS2339: Property 'getHuors' does not exist on type 'Date'. +tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(28,7): error TS2551: Property 'mesage' does not exist on type 'Error'. Did you mean 'message'? +tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(33,7): error TS2551: Property 'getHuors' does not exist on type 'Date'. Did you mean 'getHours'? ==== tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts (4 errors) ==== @@ -38,13 +38,13 @@ tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(33,7): error x.message; x.mesage; ~~~~~~ -!!! error TS2339: Property 'mesage' does not exist on type 'Error'. +!!! error TS2551: Property 'mesage' does not exist on type 'Error'. Did you mean 'message'? } if (isDate(x)) { x.getDate(); x.getHuors(); ~~~~~~~~ -!!! error TS2339: Property 'getHuors' does not exist on type 'Date'. +!!! error TS2551: Property 'getHuors' does not exist on type 'Date'. Did you mean 'getHours'? } \ No newline at end of file diff --git a/tests/baselines/reference/newExpressionWithCast.errors.txt b/tests/baselines/reference/newExpressionWithCast.errors.txt index 4fc4ee24d8c..5a2e18c585f 100644 --- a/tests/baselines/reference/newExpressionWithCast.errors.txt +++ b/tests/baselines/reference/newExpressionWithCast.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/newExpressionWithCast.ts(3,12): error TS7009: 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type. tests/cases/compiler/newExpressionWithCast.ts(7,13): error TS2365: Operator '>' cannot be applied to types 'boolean' and 'void'. tests/cases/compiler/newExpressionWithCast.ts(7,17): error TS1109: Expression expected. -tests/cases/compiler/newExpressionWithCast.ts(7,18): error TS2304: Cannot find name 'any'. +tests/cases/compiler/newExpressionWithCast.ts(7,18): error TS2693: 'any' only refers to a type, but is being used as a value here. ==== tests/cases/compiler/newExpressionWithCast.ts (4 errors) ==== @@ -19,7 +19,7 @@ tests/cases/compiler/newExpressionWithCast.ts(7,18): error TS2304: Cannot find n ~ !!! error TS1109: Expression expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. function Test3() { } // valid with noImplicitAny diff --git a/tests/baselines/reference/newNonReferenceType.errors.txt b/tests/baselines/reference/newNonReferenceType.errors.txt index a68eba9b9e7..01824a64f5f 100644 --- a/tests/baselines/reference/newNonReferenceType.errors.txt +++ b/tests/baselines/reference/newNonReferenceType.errors.txt @@ -1,12 +1,12 @@ -tests/cases/compiler/newNonReferenceType.ts(1,13): error TS2304: Cannot find name 'any'. -tests/cases/compiler/newNonReferenceType.ts(2,13): error TS2304: Cannot find name 'boolean'. +tests/cases/compiler/newNonReferenceType.ts(1,13): error TS2693: 'any' only refers to a type, but is being used as a value here. +tests/cases/compiler/newNonReferenceType.ts(2,13): error TS2693: 'boolean' only refers to a type, but is being used as a value here. ==== tests/cases/compiler/newNonReferenceType.ts (2 errors) ==== var a = new any(); ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. var b = new boolean(); // error ~~~~~~~ -!!! error TS2304: Cannot find name 'boolean'. +!!! error TS2693: 'boolean' only refers to a type, but is being used as a value here. \ No newline at end of file diff --git a/tests/baselines/reference/newOperator.errors.txt b/tests/baselines/reference/newOperator.errors.txt index fc6f22d9eac..ae96023a60b 100644 --- a/tests/baselines/reference/newOperator.errors.txt +++ b/tests/baselines/reference/newOperator.errors.txt @@ -1,10 +1,10 @@ tests/cases/compiler/newOperator.ts(3,13): error TS2693: 'ifc' only refers to a type, but is being used as a value here. tests/cases/compiler/newOperator.ts(10,10): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/compiler/newOperator.ts(11,10): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -tests/cases/compiler/newOperator.ts(12,5): error TS2304: Cannot find name 'string'. -tests/cases/compiler/newOperator.ts(18,14): error TS2304: Cannot find name 'string'. +tests/cases/compiler/newOperator.ts(12,5): error TS2693: 'string' only refers to a type, but is being used as a value here. +tests/cases/compiler/newOperator.ts(18,14): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/newOperator.ts(18,20): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/compiler/newOperator.ts(21,1): error TS2304: Cannot find name 'string'. +tests/cases/compiler/newOperator.ts(21,1): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/newOperator.ts(22,1): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. tests/cases/compiler/newOperator.ts(28,13): error TS2304: Cannot find name 'q'. tests/cases/compiler/newOperator.ts(31,10): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. @@ -32,7 +32,7 @@ tests/cases/compiler/newOperator.ts(45,23): error TS1150: 'new T[]' cannot be us !!! error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. new string; ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. // Use in LHS of expression? (new Date()).toString(); @@ -40,14 +40,14 @@ tests/cases/compiler/newOperator.ts(45,23): error TS1150: 'new T[]' cannot be us // Various spacing var t3 = new string[]( ); ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. var t4 = new string ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. [ ~ ] diff --git a/tests/baselines/reference/noImplicitAnyDestructuringInPrivateMethod.types b/tests/baselines/reference/noImplicitAnyDestructuringInPrivateMethod.types index a399e59e3c3..eb16207afed 100644 --- a/tests/baselines/reference/noImplicitAnyDestructuringInPrivateMethod.types +++ b/tests/baselines/reference/noImplicitAnyDestructuringInPrivateMethod.types @@ -10,7 +10,7 @@ export class Bar { >Bar : Bar private bar({ a, }: Arg): number { ->bar : ({a}: { a: number; }) => number +>bar : ({ a, }: { a: number; }) => number >a : number >Arg : { a: number; } @@ -22,6 +22,6 @@ export declare class Bar2 { >Bar2 : Bar2 private bar({ a, }); ->bar : ({a}: { a: any; }) => any +>bar : ({ a, }: { a: any; }) => any >a : any } diff --git a/tests/baselines/reference/objectLiteralFreshnessWithSpread.errors.txt b/tests/baselines/reference/objectLiteralFreshnessWithSpread.errors.txt new file mode 100644 index 00000000000..ac6b56f6cea --- /dev/null +++ b/tests/baselines/reference/objectLiteralFreshnessWithSpread.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/objectLiteralFreshnessWithSpread.ts(2,35): error TS2322: Type '{ z: number; b: number; extra: number; a: number; }' is not assignable to type '{ a: any; b: any; }'. + Object literal may only specify known properties, and 'z' does not exist in type '{ a: any; b: any; }'. + + +==== tests/cases/compiler/objectLiteralFreshnessWithSpread.ts (1 errors) ==== + let x = { b: 1, extra: 2 } + let xx: { a, b } = { a: 1, ...x, z: 3 } // error for 'z', no error for 'extra' + ~~~~ +!!! error TS2322: Type '{ z: number; b: number; extra: number; a: number; }' is not assignable to type '{ a: any; b: any; }'. +!!! error TS2322: Object literal may only specify known properties, and 'z' does not exist in type '{ a: any; b: any; }'. + \ No newline at end of file diff --git a/tests/baselines/reference/objectLiteralFreshnessWithSpread.js b/tests/baselines/reference/objectLiteralFreshnessWithSpread.js new file mode 100644 index 00000000000..0a4222603a2 --- /dev/null +++ b/tests/baselines/reference/objectLiteralFreshnessWithSpread.js @@ -0,0 +1,16 @@ +//// [objectLiteralFreshnessWithSpread.ts] +let x = { b: 1, extra: 2 } +let xx: { a, b } = { a: 1, ...x, z: 3 } // error for 'z', no error for 'extra' + + +//// [objectLiteralFreshnessWithSpread.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var x = { b: 1, extra: 2 }; +var xx = __assign({ a: 1 }, x, { z: 3 }); // error for 'z', no error for 'extra' diff --git a/tests/baselines/reference/objectRest.types b/tests/baselines/reference/objectRest.types index 2fff9a3c729..dff8830e818 100644 --- a/tests/baselines/reference/objectRest.types +++ b/tests/baselines/reference/objectRest.types @@ -218,8 +218,8 @@ var { [computed]: stillNotGreat, [computed2]: soSo, ...o } = o; >o : { a: number; b: string; } var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes; ->noContextualType : ({aNumber, ...notEmptyObject}: { [x: string]: any; aNumber?: number; }) => any ->({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes : ({aNumber, ...notEmptyObject}: { [x: string]: any; aNumber?: number; }) => any +>noContextualType : ({ aNumber, ...notEmptyObject }: { [x: string]: any; aNumber?: number; }) => any +>({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes : ({ aNumber, ...notEmptyObject }: { [x: string]: any; aNumber?: number; }) => any >aNumber : number >12 : 12 >notEmptyObject : { [x: string]: any; } diff --git a/tests/baselines/reference/objectRestParameter.types b/tests/baselines/reference/objectRestParameter.types index e56e7cebfc7..3d0d1bb619b 100644 --- a/tests/baselines/reference/objectRestParameter.types +++ b/tests/baselines/reference/objectRestParameter.types @@ -1,6 +1,6 @@ === tests/cases/conformance/types/rest/objectRestParameter.ts === function cloneAgain({ a, ...clone }: { a: number, b: string }): void { ->cloneAgain : ({a, ...clone}: { a: number; b: string; }) => void +>cloneAgain : ({ a, ...clone }: { a: number; b: string; }) => void >a : number >clone : { b: string; } >a : number @@ -19,7 +19,7 @@ declare function suddenly(f: (a: { x: { z, ka }, y: string }) => void); suddenly(({ x: a, ...rest }) => rest.y); >suddenly(({ x: a, ...rest }) => rest.y) : any >suddenly : (f: (a: { x: { z: any; ka: any; }; y: string; }) => void) => any ->({ x: a, ...rest }) => rest.y : ({x: a, ...rest}: { x: { z: any; ka: any; }; y: string; }) => string +>({ x: a, ...rest }) => rest.y : ({ x: a, ...rest }: { x: { z: any; ka: any; }; y: string; }) => string >x : any >a : { z: any; ka: any; } >rest : { y: string; } @@ -30,7 +30,7 @@ suddenly(({ x: a, ...rest }) => rest.y); suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); >suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka) : any >suddenly : (f: (a: { x: { z: any; ka: any; }; y: string; }) => void) => any ->({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka : ({x: {z, ...nested}, ...rest}?: { x: { z: any; ka: any; }; y: string; }) => string +>({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka : ({ x: { z, ...nested }, ...rest }?: { x: { z: any; ka: any; }; y: string; }) => string >x : any >z : any >12 : 12 @@ -57,7 +57,7 @@ class C { >C : C m({ a, ...clone }: { a: number, b: string}): void { ->m : ({a, ...clone}: { a: number; b: string; }) => void +>m : ({ a, ...clone }: { a: number; b: string; }) => void >a : number >clone : { b: string; } >a : number @@ -76,7 +76,7 @@ class C { } } function foobar({ bar={}, ...opts }: any = {}) { ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void >bar : {} >{} : {} >opts : any @@ -84,18 +84,18 @@ function foobar({ bar={}, ...opts }: any = {}) { } foobar(); >foobar() : void ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void foobar({ baz: 'hello' }); >foobar({ baz: 'hello' }) : void ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void >{ baz: 'hello' } : { baz: string; } >baz : string >'hello' : "hello" foobar({ bar: { greeting: 'hello' } }); >foobar({ bar: { greeting: 'hello' } }) : void ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void >{ bar: { greeting: 'hello' } } : { bar: { greeting: string; }; } >bar : { greeting: string; } >{ greeting: 'hello' } : { greeting: string; } diff --git a/tests/baselines/reference/objectRestParameterES5.types b/tests/baselines/reference/objectRestParameterES5.types index 009d810782b..e0ebee39317 100644 --- a/tests/baselines/reference/objectRestParameterES5.types +++ b/tests/baselines/reference/objectRestParameterES5.types @@ -1,6 +1,6 @@ === tests/cases/conformance/types/rest/objectRestParameterES5.ts === function cloneAgain({ a, ...clone }: { a: number, b: string }): void { ->cloneAgain : ({a, ...clone}: { a: number; b: string; }) => void +>cloneAgain : ({ a, ...clone }: { a: number; b: string; }) => void >a : number >clone : { b: string; } >a : number @@ -19,7 +19,7 @@ declare function suddenly(f: (a: { x: { z, ka }, y: string }) => void); suddenly(({ x: a, ...rest }) => rest.y); >suddenly(({ x: a, ...rest }) => rest.y) : any >suddenly : (f: (a: { x: { z: any; ka: any; }; y: string; }) => void) => any ->({ x: a, ...rest }) => rest.y : ({x: a, ...rest}: { x: { z: any; ka: any; }; y: string; }) => string +>({ x: a, ...rest }) => rest.y : ({ x: a, ...rest }: { x: { z: any; ka: any; }; y: string; }) => string >x : any >a : { z: any; ka: any; } >rest : { y: string; } @@ -30,7 +30,7 @@ suddenly(({ x: a, ...rest }) => rest.y); suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); >suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka) : any >suddenly : (f: (a: { x: { z: any; ka: any; }; y: string; }) => void) => any ->({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka : ({x: {z, ...nested}, ...rest}?: { x: { z: any; ka: any; }; y: string; }) => string +>({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka : ({ x: { z, ...nested }, ...rest }?: { x: { z: any; ka: any; }; y: string; }) => string >x : any >z : any >12 : 12 @@ -57,7 +57,7 @@ class C { >C : C m({ a, ...clone }: { a: number, b: string}): void { ->m : ({a, ...clone}: { a: number; b: string; }) => void +>m : ({ a, ...clone }: { a: number; b: string; }) => void >a : number >clone : { b: string; } >a : number @@ -76,7 +76,7 @@ class C { } } function foobar({ bar={}, ...opts }: any = {}) { ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void >bar : {} >{} : {} >opts : any @@ -84,18 +84,18 @@ function foobar({ bar={}, ...opts }: any = {}) { } foobar(); >foobar() : void ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void foobar({ baz: 'hello' }); >foobar({ baz: 'hello' }) : void ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void >{ baz: 'hello' } : { baz: string; } >baz : string >'hello' : "hello" foobar({ bar: { greeting: 'hello' } }); >foobar({ bar: { greeting: 'hello' } }) : void ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void >{ bar: { greeting: 'hello' } } : { bar: { greeting: string; }; } >bar : { greeting: string; } >{ greeting: 'hello' } : { greeting: string; } diff --git a/tests/baselines/reference/objectSpreadStrictNull.errors.txt b/tests/baselines/reference/objectSpreadStrictNull.errors.txt new file mode 100644 index 00000000000..f3c5cc7de25 --- /dev/null +++ b/tests/baselines/reference/objectSpreadStrictNull.errors.txt @@ -0,0 +1,84 @@ +tests/cases/conformance/types/spread/objectSpreadStrictNull.ts(9,9): error TS2322: Type '{ sn: string | number | undefined; }' is not assignable to type '{ sn: string | number; }'. + Types of property 'sn' are incompatible. + Type 'string | number | undefined' is not assignable to type 'string | number'. + Type 'undefined' is not assignable to type 'string | number'. +tests/cases/conformance/types/spread/objectSpreadStrictNull.ts(10,9): error TS2322: Type '{ sn: string | number | undefined; }' is not assignable to type '{ sn: string | number; }'. + Types of property 'sn' are incompatible. + Type 'string | number | undefined' is not assignable to type 'string | number'. + Type 'undefined' is not assignable to type 'string | number'. +tests/cases/conformance/types/spread/objectSpreadStrictNull.ts(14,9): error TS2322: Type '{ sn: number | undefined; }' is not assignable to type '{ sn: string | number; }'. + Types of property 'sn' are incompatible. + Type 'number | undefined' is not assignable to type 'string | number'. + Type 'undefined' is not assignable to type 'string | number'. +tests/cases/conformance/types/spread/objectSpreadStrictNull.ts(15,9): error TS2322: Type '{ sn: number | undefined; }' is not assignable to type '{ sn: string | number; }'. + Types of property 'sn' are incompatible. + Type 'number | undefined' is not assignable to type 'string | number'. + Type 'undefined' is not assignable to type 'string | number'. +tests/cases/conformance/types/spread/objectSpreadStrictNull.ts(18,9): error TS2322: Type '{ sn: string | number | undefined; }' is not assignable to type '{ sn: string | number | boolean; }'. + Types of property 'sn' are incompatible. + Type 'string | number | undefined' is not assignable to type 'string | number | boolean'. + Type 'undefined' is not assignable to type 'string | number | boolean'. +tests/cases/conformance/types/spread/objectSpreadStrictNull.ts(28,7): error TS2322: Type '{ title: undefined; yearReleased: number; }' is not assignable to type 'Movie'. + Types of property 'title' are incompatible. + Type 'undefined' is not assignable to type 'string'. + + +==== tests/cases/conformance/types/spread/objectSpreadStrictNull.ts (6 errors) ==== + function f( + definiteBoolean: { sn: boolean }, + definiteString: { sn: string }, + optionalString: { sn?: string }, + optionalNumber: { sn?: number }, + undefinedString: { sn: string | undefined }, + undefinedNumber: { sn: number | undefined }) { + // optional + let optionalUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; + ~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ sn: string | number | undefined; }' is not assignable to type '{ sn: string | number; }'. +!!! error TS2322: Types of property 'sn' are incompatible. +!!! error TS2322: Type 'string | number | undefined' is not assignable to type 'string | number'. +!!! error TS2322: Type 'undefined' is not assignable to type 'string | number'. + let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; + ~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ sn: string | number | undefined; }' is not assignable to type '{ sn: string | number; }'. +!!! error TS2322: Types of property 'sn' are incompatible. +!!! error TS2322: Type 'string | number | undefined' is not assignable to type 'string | number'. +!!! error TS2322: Type 'undefined' is not assignable to type 'string | number'. + let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; + + // undefined + let undefinedUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedNumber }; + ~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ sn: number | undefined; }' is not assignable to type '{ sn: string | number; }'. +!!! error TS2322: Types of property 'sn' are incompatible. +!!! error TS2322: Type 'number | undefined' is not assignable to type 'string | number'. +!!! error TS2322: Type 'undefined' is not assignable to type 'string | number'. + let undefinedUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedString, ...undefinedNumber }; + ~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ sn: number | undefined; }' is not assignable to type '{ sn: string | number; }'. +!!! error TS2322: Types of property 'sn' are incompatible. +!!! error TS2322: Type 'number | undefined' is not assignable to type 'string | number'. +!!! error TS2322: Type 'undefined' is not assignable to type 'string | number'. + let allUndefined: { sn: string | number | undefined } = { ...undefinedString, ...undefinedNumber }; + + let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ sn: string | number | undefined; }' is not assignable to type '{ sn: string | number | boolean; }'. +!!! error TS2322: Types of property 'sn' are incompatible. +!!! error TS2322: Type 'string | number | undefined' is not assignable to type 'string | number | boolean'. +!!! error TS2322: Type 'undefined' is not assignable to type 'string | number | boolean'. + } + + type Movie = { + title: string; + yearReleased: number; + } + + const m = { title: "The Matrix", yearReleased: 1999 }; + // should error here because title: undefined is not assignable to string + const x: Movie = { ...m, title: undefined }; + ~ +!!! error TS2322: Type '{ title: undefined; yearReleased: number; }' is not assignable to type 'Movie'. +!!! error TS2322: Types of property 'title' are incompatible. +!!! error TS2322: Type 'undefined' is not assignable to type 'string'. + \ No newline at end of file diff --git a/tests/baselines/reference/objectSpreadStrictNull.js b/tests/baselines/reference/objectSpreadStrictNull.js index 8a4cf0e5f9f..a21b5e2467c 100644 --- a/tests/baselines/reference/objectSpreadStrictNull.js +++ b/tests/baselines/reference/objectSpreadStrictNull.js @@ -18,6 +18,15 @@ function f( let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; } + +type Movie = { + title: string; + yearReleased: number; +} + +const m = { title: "The Matrix", yearReleased: 1999 }; +// should error here because title: undefined is not assignable to string +const x: Movie = { ...m, title: undefined }; //// [objectSpreadStrictNull.js] @@ -40,3 +49,6 @@ function f(definiteBoolean, definiteString, optionalString, optionalNumber, unde var allUndefined = __assign({}, undefinedString, undefinedNumber); var undefinedWithOptionalContinues = __assign({}, definiteBoolean, undefinedString, optionalNumber); } +var m = { title: "The Matrix", yearReleased: 1999 }; +// should error here because title: undefined is not assignable to string +var x = __assign({}, m, { title: undefined }); diff --git a/tests/baselines/reference/objectSpreadStrictNull.symbols b/tests/baselines/reference/objectSpreadStrictNull.symbols deleted file mode 100644 index e9202767945..00000000000 --- a/tests/baselines/reference/objectSpreadStrictNull.symbols +++ /dev/null @@ -1,80 +0,0 @@ -=== tests/cases/conformance/types/spread/objectSpreadStrictNull.ts === -function f( ->f : Symbol(f, Decl(objectSpreadStrictNull.ts, 0, 0)) - - definiteBoolean: { sn: boolean }, ->definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 0, 11)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 1, 22)) - - definiteString: { sn: string }, ->definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 1, 37)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 2, 21)) - - optionalString: { sn?: string }, ->optionalString : Symbol(optionalString, Decl(objectSpreadStrictNull.ts, 2, 35)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 3, 21)) - - optionalNumber: { sn?: number }, ->optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 3, 36)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 4, 21)) - - undefinedString: { sn: string | undefined }, ->undefinedString : Symbol(undefinedString, Decl(objectSpreadStrictNull.ts, 4, 36)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 5, 22)) - - undefinedNumber: { sn: number | undefined }) { ->undefinedNumber : Symbol(undefinedNumber, Decl(objectSpreadStrictNull.ts, 5, 48)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 6, 22)) - - // optional - let optionalUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; ->optionalUnionStops : Symbol(optionalUnionStops, Decl(objectSpreadStrictNull.ts, 8, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 8, 29)) ->definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 0, 11)) ->definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 1, 37)) ->optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 3, 36)) - - let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; ->optionalUnionDuplicates : Symbol(optionalUnionDuplicates, Decl(objectSpreadStrictNull.ts, 9, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 9, 34)) ->definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 0, 11)) ->definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 1, 37)) ->optionalString : Symbol(optionalString, Decl(objectSpreadStrictNull.ts, 2, 35)) ->optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 3, 36)) - - let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; ->allOptional : Symbol(allOptional, Decl(objectSpreadStrictNull.ts, 10, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 10, 22)) ->optionalString : Symbol(optionalString, Decl(objectSpreadStrictNull.ts, 2, 35)) ->optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 3, 36)) - - // undefined - let undefinedUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedNumber }; ->undefinedUnionStops : Symbol(undefinedUnionStops, Decl(objectSpreadStrictNull.ts, 13, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 13, 30)) ->definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 0, 11)) ->definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 1, 37)) ->undefinedNumber : Symbol(undefinedNumber, Decl(objectSpreadStrictNull.ts, 5, 48)) - - let undefinedUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedString, ...undefinedNumber }; ->undefinedUnionDuplicates : Symbol(undefinedUnionDuplicates, Decl(objectSpreadStrictNull.ts, 14, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 14, 35)) ->definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 0, 11)) ->definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 1, 37)) ->undefinedString : Symbol(undefinedString, Decl(objectSpreadStrictNull.ts, 4, 36)) ->undefinedNumber : Symbol(undefinedNumber, Decl(objectSpreadStrictNull.ts, 5, 48)) - - let allUndefined: { sn: string | number | undefined } = { ...undefinedString, ...undefinedNumber }; ->allUndefined : Symbol(allUndefined, Decl(objectSpreadStrictNull.ts, 15, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 15, 23)) ->undefinedString : Symbol(undefinedString, Decl(objectSpreadStrictNull.ts, 4, 36)) ->undefinedNumber : Symbol(undefinedNumber, Decl(objectSpreadStrictNull.ts, 5, 48)) - - let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; ->undefinedWithOptionalContinues : Symbol(undefinedWithOptionalContinues, Decl(objectSpreadStrictNull.ts, 17, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 17, 41)) ->definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 0, 11)) ->undefinedString : Symbol(undefinedString, Decl(objectSpreadStrictNull.ts, 4, 36)) ->optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 3, 36)) -} - diff --git a/tests/baselines/reference/objectSpreadStrictNull.types b/tests/baselines/reference/objectSpreadStrictNull.types deleted file mode 100644 index f70f0a9cad2..00000000000 --- a/tests/baselines/reference/objectSpreadStrictNull.types +++ /dev/null @@ -1,87 +0,0 @@ -=== tests/cases/conformance/types/spread/objectSpreadStrictNull.ts === -function f( ->f : (definiteBoolean: { sn: boolean; }, definiteString: { sn: string; }, optionalString: { sn?: string | undefined; }, optionalNumber: { sn?: number | undefined; }, undefinedString: { sn: string | undefined; }, undefinedNumber: { sn: number | undefined; }) => void - - definiteBoolean: { sn: boolean }, ->definiteBoolean : { sn: boolean; } ->sn : boolean - - definiteString: { sn: string }, ->definiteString : { sn: string; } ->sn : string - - optionalString: { sn?: string }, ->optionalString : { sn?: string | undefined; } ->sn : string | undefined - - optionalNumber: { sn?: number }, ->optionalNumber : { sn?: number | undefined; } ->sn : number | undefined - - undefinedString: { sn: string | undefined }, ->undefinedString : { sn: string | undefined; } ->sn : string | undefined - - undefinedNumber: { sn: number | undefined }) { ->undefinedNumber : { sn: number | undefined; } ->sn : number | undefined - - // optional - let optionalUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; ->optionalUnionStops : { sn: string | number; } ->sn : string | number ->{ ...definiteBoolean, ...definiteString, ...optionalNumber } : { sn: string | number; } ->definiteBoolean : { sn: boolean; } ->definiteString : { sn: string; } ->optionalNumber : { sn?: number | undefined; } - - let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; ->optionalUnionDuplicates : { sn: string | number; } ->sn : string | number ->{ ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber } : { sn: string | number; } ->definiteBoolean : { sn: boolean; } ->definiteString : { sn: string; } ->optionalString : { sn?: string | undefined; } ->optionalNumber : { sn?: number | undefined; } - - let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; ->allOptional : { sn?: string | number | undefined; } ->sn : string | number | undefined ->{ ...optionalString, ...optionalNumber } : { sn?: string | number | undefined; } ->optionalString : { sn?: string | undefined; } ->optionalNumber : { sn?: number | undefined; } - - // undefined - let undefinedUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedNumber }; ->undefinedUnionStops : { sn: string | number; } ->sn : string | number ->{ ...definiteBoolean, ...definiteString, ...undefinedNumber } : { sn: string | number; } ->definiteBoolean : { sn: boolean; } ->definiteString : { sn: string; } ->undefinedNumber : { sn: number | undefined; } - - let undefinedUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedString, ...undefinedNumber }; ->undefinedUnionDuplicates : { sn: string | number; } ->sn : string | number ->{ ...definiteBoolean, ...definiteString, ...undefinedString, ...undefinedNumber } : { sn: string | number; } ->definiteBoolean : { sn: boolean; } ->definiteString : { sn: string; } ->undefinedString : { sn: string | undefined; } ->undefinedNumber : { sn: number | undefined; } - - let allUndefined: { sn: string | number | undefined } = { ...undefinedString, ...undefinedNumber }; ->allUndefined : { sn: string | number | undefined; } ->sn : string | number | undefined ->{ ...undefinedString, ...undefinedNumber } : { sn: string | number | undefined; } ->undefinedString : { sn: string | undefined; } ->undefinedNumber : { sn: number | undefined; } - - let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; ->undefinedWithOptionalContinues : { sn: string | number | boolean; } ->sn : string | number | boolean ->{ ...definiteBoolean, ...undefinedString, ...optionalNumber } : { sn: string | number | boolean; } ->definiteBoolean : { sn: boolean; } ->undefinedString : { sn: string | undefined; } ->optionalNumber : { sn?: number | undefined; } -} - diff --git a/tests/baselines/reference/optionalParamArgsTest.errors.txt b/tests/baselines/reference/optionalParamArgsTest.errors.txt index 05fefa85065..7a3e044e6fd 100644 --- a/tests/baselines/reference/optionalParamArgsTest.errors.txt +++ b/tests/baselines/reference/optionalParamArgsTest.errors.txt @@ -1,25 +1,25 @@ tests/cases/compiler/optionalParamArgsTest.ts(31,12): error TS2393: Duplicate function implementation. tests/cases/compiler/optionalParamArgsTest.ts(34,12): error TS2393: Duplicate function implementation. -tests/cases/compiler/optionalParamArgsTest.ts(98,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(99,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(100,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(101,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(102,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(103,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(104,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(105,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(106,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(107,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(108,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(109,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(110,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(111,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(112,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(113,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(114,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(115,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(116,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(117,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/optionalParamArgsTest.ts(98,1): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/optionalParamArgsTest.ts(99,1): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/optionalParamArgsTest.ts(100,1): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/optionalParamArgsTest.ts(101,1): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/optionalParamArgsTest.ts(102,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(103,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(104,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(105,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(106,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/compiler/optionalParamArgsTest.ts(107,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/compiler/optionalParamArgsTest.ts(108,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/compiler/optionalParamArgsTest.ts(109,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/compiler/optionalParamArgsTest.ts(110,1): error TS2554: Expected 0-2 arguments, but got 3. +tests/cases/compiler/optionalParamArgsTest.ts(111,1): error TS2554: Expected 0-2 arguments, but got 3. +tests/cases/compiler/optionalParamArgsTest.ts(112,1): error TS2554: Expected 0-2 arguments, but got 3. +tests/cases/compiler/optionalParamArgsTest.ts(113,1): error TS2554: Expected 0-2 arguments, but got 3. +tests/cases/compiler/optionalParamArgsTest.ts(114,1): error TS2554: Expected 1-2 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(115,1): error TS2554: Expected 1-2 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(116,1): error TS2554: Expected 1-2 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(117,1): error TS2554: Expected 1-2 arguments, but got 0. ==== tests/cases/compiler/optionalParamArgsTest.ts (22 errors) ==== @@ -126,64 +126,64 @@ tests/cases/compiler/optionalParamArgsTest.ts(117,1): error TS2346: Supplied par // Negative tests - we expect these cases to fail c1o1.C1M1(1); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. i1o1.C1M1(1); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. F1(1); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. L1(1); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. c1o1.C1M2(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. i1o1.C1M2(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. F2(); ~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. L2(); ~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. c1o1.C1M2(1,2); ~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. i1o1.C1M2(1,2); ~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. F2(1,2); ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. L2(1,2); ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. c1o1.C1M3(1,2,3); ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0-2 arguments, but got 3. i1o1.C1M3(1,2,3); ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0-2 arguments, but got 3. F3(1,2,3); ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0-2 arguments, but got 3. L3(1,2,3); ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0-2 arguments, but got 3. c1o1.C1M4(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 0. i1o1.C1M4(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 0. F4(); ~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 0. L4(); ~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 0. function fnOpt1(id: number, children: number[] = [], expectedPath: number[] = [], isRoot?: boolean): void {} function fnOpt2(id: number, children?: number[], expectedPath?: number[], isRoot?: boolean): void {} diff --git a/tests/baselines/reference/overload1.errors.txt b/tests/baselines/reference/overload1.errors.txt index a88b4f81519..2f118e59f64 100644 --- a/tests/baselines/reference/overload1.errors.txt +++ b/tests/baselines/reference/overload1.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/overload1.ts(27,5): error TS2322: Type 'C' is not assignable to type 'string'. tests/cases/compiler/overload1.ts(29,1): error TS2322: Type 'number' is not assignable to type 'string'. -tests/cases/compiler/overload1.ts(31,3): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/overload1.ts(32,3): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/overload1.ts(31,3): error TS2554: Expected 1-2 arguments, but got 3. +tests/cases/compiler/overload1.ts(32,3): error TS2554: Expected 1-2 arguments, but got 0. tests/cases/compiler/overload1.ts(33,1): error TS2322: Type 'C' is not assignable to type 'string'. tests/cases/compiler/overload1.ts(34,9): error TS2345: Argument of type '2' is not assignable to parameter of type 'string'. @@ -43,10 +43,10 @@ tests/cases/compiler/overload1.ts(34,9): error TS2345: Argument of type '2' is n var z:string=x.g(x.g(3,3)); // good z=x.g(2,2,2); // no match ~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 3. z=x.g(); // no match ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 0. z=x.g(new O.B()); // ambiguous (up and down conversion) ~ !!! error TS2322: Type 'C' is not assignable to type 'string'. diff --git a/tests/baselines/reference/overloadResolution.errors.txt b/tests/baselines/reference/overloadResolution.errors.txt index b8b2cdfe888..37cea935e66 100644 --- a/tests/baselines/reference/overloadResolution.errors.txt +++ b/tests/baselines/reference/overloadResolution.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(27,5): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(41,11): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(63,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(63,1): error TS2558: Expected 1-3 type arguments, but got 4. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(70,21): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(71,21): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(81,5): error TS2344: Type 'boolean' does not satisfy the constraint 'number'. @@ -79,7 +79,7 @@ tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(91,22): // Generic overloads with differing arity called with type argument count that doesn't match any overload fn3(); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 1-3 type arguments, but got 4. // Generic overloads with constraints called with type arguments that satisfy the constraints function fn4(n: T, m: U); diff --git a/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt b/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt index 4c8e9b2513a..92f3a7cfa90 100644 --- a/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt +++ b/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(27,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(60,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(61,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(65,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(60,1): error TS2558: Expected 3 type arguments, but got 1. +tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(61,1): error TS2558: Expected 3 type arguments, but got 2. +tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(65,1): error TS2558: Expected 3 type arguments, but got 4. tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(73,25): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(74,9): error TS2344: Type 'number' does not satisfy the constraint 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(75,9): error TS2344: Type 'number' does not satisfy the constraint 'string'. @@ -78,16 +78,16 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstru // Generic overloads with differing arity called with type arguments matching each overload type parameter count new fn3(4); // Error ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 3 type arguments, but got 1. new fn3('', '', ''); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 3 type arguments, but got 2. new fn3('', '', 3); // Generic overloads with differing arity called with type argument count that doesn't match any overload new fn3(); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 3 type arguments, but got 4. // Generic overloads with constraints called with type arguments that satisfy the constraints class fn4 { diff --git a/tests/baselines/reference/overloadResolutionConstructors.errors.txt b/tests/baselines/reference/overloadResolutionConstructors.errors.txt index 9a112eaf2ef..9b09992228e 100644 --- a/tests/baselines/reference/overloadResolutionConstructors.errors.txt +++ b/tests/baselines/reference/overloadResolutionConstructors.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(27,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(43,15): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(67,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(67,1): error TS2558: Expected 1-3 type arguments, but got 4. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(77,25): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(78,25): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(88,9): error TS2344: Type 'boolean' does not satisfy the constraint 'number'. @@ -83,7 +83,7 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors // Generic overloads with differing arity called with type argument count that doesn't match any overload new fn3(); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 1-3 type arguments, but got 4. // Generic overloads with constraints called with type arguments that satisfy the constraints interface fn4 { diff --git a/tests/baselines/reference/overloadResolutionOnDefaultConstructor1.errors.txt b/tests/baselines/reference/overloadResolutionOnDefaultConstructor1.errors.txt index 1922df6852a..bdbc2310fb1 100644 --- a/tests/baselines/reference/overloadResolutionOnDefaultConstructor1.errors.txt +++ b/tests/baselines/reference/overloadResolutionOnDefaultConstructor1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/overloadResolutionOnDefaultConstructor1.ts(3,16): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/overloadResolutionOnDefaultConstructor1.ts(3,16): error TS2554: Expected 0 arguments, but got 1. ==== tests/cases/compiler/overloadResolutionOnDefaultConstructor1.ts (1 errors) ==== @@ -6,6 +6,6 @@ tests/cases/compiler/overloadResolutionOnDefaultConstructor1.ts(3,16): error TS2 public clone() { return new Bar(0); ~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. } } \ No newline at end of file diff --git a/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt b/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt index ae16b59b095..cded9c44a3d 100644 --- a/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt +++ b/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt @@ -5,12 +5,12 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,3): error TS1128 tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,10): error TS2304: Cannot find name 'test'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,15): error TS2304: Cannot find name 'name'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,19): error TS1005: ',' expected. -tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,20): error TS2304: Cannot find name 'string'. +tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,20): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,3): error TS1128: Declaration or statement expected. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,10): error TS2304: Cannot find name 'test'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,15): error TS2304: Cannot find name 'name'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,20): error TS1109: Expression expected. -tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,21): error TS2304: Cannot find name 'any'. +tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,21): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,25): error TS1005: ';' expected. @@ -33,7 +33,7 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,25): error TS100 ~ !!! error TS1005: ',' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. static test(name?:any){ } ~~~~~~ !!! error TS1128: Declaration or statement expected. @@ -44,7 +44,7 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,25): error TS100 ~ !!! error TS1109: Expression expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. } \ No newline at end of file diff --git a/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt b/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt index 64faaf7e8c1..52bcaaf790b 100644 --- a/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt +++ b/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(5,1): error TS2558: Expected 0-2 type arguments, but got 3. tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2350: Only a void function can be called with the 'new' keyword. +tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2558: Expected 0-2 type arguments, but got 3. ==== tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts (3 errors) ==== @@ -10,9 +10,9 @@ tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2350: Callbacks('s'); // wrong number of type arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0-2 type arguments, but got 3. new Callbacks('s'); // wrong number of type arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2350: Only a void function can be called with the 'new' keyword. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2350: Only a void function can be called with the 'new' keyword. \ No newline at end of file +!!! error TS2558: Expected 0-2 type arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types b/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types index 46b5983a514..d276812c01d 100644 --- a/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types +++ b/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types @@ -10,7 +10,7 @@ interface Foo { } function foobar({ bar = {}, ...opts }: Foo = {}) { ->foobar : ({bar, ...opts}?: Foo) => void +>foobar : ({ bar, ...opts }?: Foo) => void >bar : any >{} : {} >opts : { baz?: any; } diff --git a/tests/baselines/reference/parameterNamesInTypeParameterList.errors.txt b/tests/baselines/reference/parameterNamesInTypeParameterList.errors.txt index 54ddb963f94..c4e29ca62f9 100644 --- a/tests/baselines/reference/parameterNamesInTypeParameterList.errors.txt +++ b/tests/baselines/reference/parameterNamesInTypeParameterList.errors.txt @@ -1,44 +1,44 @@ -tests/cases/compiler/parameterNamesInTypeParameterList.ts(1,30): error TS2304: Cannot find name 'a'. -tests/cases/compiler/parameterNamesInTypeParameterList.ts(5,30): error TS2304: Cannot find name 'a'. -tests/cases/compiler/parameterNamesInTypeParameterList.ts(9,30): error TS2304: Cannot find name 'a'. -tests/cases/compiler/parameterNamesInTypeParameterList.ts(14,22): error TS2304: Cannot find name 'a'. -tests/cases/compiler/parameterNamesInTypeParameterList.ts(17,22): error TS2304: Cannot find name 'a'. -tests/cases/compiler/parameterNamesInTypeParameterList.ts(20,22): error TS2304: Cannot find name 'a'. +tests/cases/compiler/parameterNamesInTypeParameterList.ts(1,30): error TS2552: Cannot find name 'a'. Did you mean 'A'? +tests/cases/compiler/parameterNamesInTypeParameterList.ts(5,30): error TS2552: Cannot find name 'a'. Did you mean 'A'? +tests/cases/compiler/parameterNamesInTypeParameterList.ts(9,30): error TS2552: Cannot find name 'a'. Did you mean 'A'? +tests/cases/compiler/parameterNamesInTypeParameterList.ts(14,22): error TS2552: Cannot find name 'a'. Did you mean 'A'? +tests/cases/compiler/parameterNamesInTypeParameterList.ts(17,22): error TS2552: Cannot find name 'a'. Did you mean 'A'? +tests/cases/compiler/parameterNamesInTypeParameterList.ts(20,22): error TS2552: Cannot find name 'a'. Did you mean 'A'? ==== tests/cases/compiler/parameterNamesInTypeParameterList.ts (6 errors) ==== function f0(a: T) { ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? a.b; } function f1({a}: {a:T}) { ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? a.b; } function f2([a]: T[]) { ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? a.b; } class A { m0(a: T) { ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? a.b } m1({a}: {a:T}) { ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? a.b } m2([a]: T[]) { ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? a.b } } \ No newline at end of file diff --git a/tests/baselines/reference/parserAmbiguity1.errors.txt b/tests/baselines/reference/parserAmbiguity1.errors.txt index 00126360794..a5360161147 100644 --- a/tests/baselines/reference/parserAmbiguity1.errors.txt +++ b/tests/baselines/reference/parserAmbiguity1.errors.txt @@ -1,10 +1,16 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguity1.ts(1,1): error TS2304: Cannot find name 'f'. tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguity1.ts(1,3): error TS2304: Cannot find name 'g'. +tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguity1.ts(1,5): error TS2304: Cannot find name 'A'. +tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguity1.ts(1,8): error TS2304: Cannot find name 'B'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguity1.ts (2 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguity1.ts (4 errors) ==== f(g(7)); ~ !!! error TS2304: Cannot find name 'f'. ~ -!!! error TS2304: Cannot find name 'g'. \ No newline at end of file +!!! error TS2304: Cannot find name 'g'. + ~ +!!! error TS2304: Cannot find name 'A'. + ~ +!!! error TS2304: Cannot find name 'B'. \ No newline at end of file diff --git a/tests/baselines/reference/parserAmbiguityWithBinaryOperator4.errors.txt b/tests/baselines/reference/parserAmbiguityWithBinaryOperator4.errors.txt index 2c7bef61598..41147305ce0 100644 --- a/tests/baselines/reference/parserAmbiguityWithBinaryOperator4.errors.txt +++ b/tests/baselines/reference/parserAmbiguityWithBinaryOperator4.errors.txt @@ -1,10 +1,16 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts(3,9): error TS2347: Untyped function calls may not accept type arguments. +tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts(3,11): error TS2304: Cannot find name 'b'. +tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts(3,14): error TS2304: Cannot find name 'b'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts (1 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts (3 errors) ==== function g() { var a, b, c; if (a(c + 1)) { } ~~~~~~~~~~~~~~ !!! error TS2347: Untyped function calls may not accept type arguments. + ~ +!!! error TS2304: Cannot find name 'b'. + ~ +!!! error TS2304: Cannot find name 'b'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt b/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt index 821451c00c8..c13916fa39d 100644 --- a/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt +++ b/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,1): error TS2558: Expected 0 type arguments, but got 1. tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,10): error TS2304: Cannot find name 'A'. tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,12): error TS1005: '(' expected. @@ -6,7 +6,7 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3. ==== tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts (3 errors) ==== new Date ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. ~ !!! error TS2304: Cannot find name 'A'. diff --git a/tests/baselines/reference/parserGenericConstraint4.errors.txt b/tests/baselines/reference/parserGenericConstraint4.errors.txt index b42570593f7..f829bad913f 100644 --- a/tests/baselines/reference/parserGenericConstraint4.errors.txt +++ b/tests/baselines/reference/parserGenericConstraint4.errors.txt @@ -1,8 +1,11 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint4.ts(1,19): error TS2304: Cannot find name 'List'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint4.ts(1,24): error TS2304: Cannot find name 'List'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint4.ts (1 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint4.ts (2 errors) ==== class C > > { ~~~~ +!!! error TS2304: Cannot find name 'List'. + ~~~~ !!! error TS2304: Cannot find name 'List'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericConstraint5.errors.txt b/tests/baselines/reference/parserGenericConstraint5.errors.txt index 3479731ae13..a20e617f5e6 100644 --- a/tests/baselines/reference/parserGenericConstraint5.errors.txt +++ b/tests/baselines/reference/parserGenericConstraint5.errors.txt @@ -1,8 +1,11 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint5.ts(1,19): error TS2304: Cannot find name 'List'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint5.ts(1,24): error TS2304: Cannot find name 'List'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint5.ts (1 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint5.ts (2 errors) ==== class C> > { ~~~~ +!!! error TS2304: Cannot find name 'List'. + ~~~~ !!! error TS2304: Cannot find name 'List'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericConstraint6.errors.txt b/tests/baselines/reference/parserGenericConstraint6.errors.txt index 5efbcc8e8d0..be90daff826 100644 --- a/tests/baselines/reference/parserGenericConstraint6.errors.txt +++ b/tests/baselines/reference/parserGenericConstraint6.errors.txt @@ -1,8 +1,11 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint6.ts(1,19): error TS2304: Cannot find name 'List'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint6.ts(1,24): error TS2304: Cannot find name 'List'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint6.ts (1 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint6.ts (2 errors) ==== class C >> { ~~~~ +!!! error TS2304: Cannot find name 'List'. + ~~~~ !!! error TS2304: Cannot find name 'List'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericConstraint7.errors.txt b/tests/baselines/reference/parserGenericConstraint7.errors.txt index ffff8ea2583..99054892fc0 100644 --- a/tests/baselines/reference/parserGenericConstraint7.errors.txt +++ b/tests/baselines/reference/parserGenericConstraint7.errors.txt @@ -1,8 +1,11 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint7.ts(1,19): error TS2304: Cannot find name 'List'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint7.ts(1,24): error TS2304: Cannot find name 'List'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint7.ts (1 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint7.ts (2 errors) ==== class C>> { ~~~~ +!!! error TS2304: Cannot find name 'List'. + ~~~~ !!! error TS2304: Cannot find name 'List'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt b/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt index 477cc3edcdc..fb7dbacf656 100644 --- a/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt +++ b/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt @@ -1,47 +1,74 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(1,17): error TS2304: Cannot find name 'A'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(1,19): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(1,33): error TS2304: Cannot find name 'B'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(1,35): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(4,9): error TS2315: Type 'C' is not generic. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(4,11): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(5,9): error TS2304: Cannot find name 'D'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(5,11): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(6,9): error TS2503: Cannot find namespace 'E'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(6,13): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(7,9): error TS2503: Cannot find namespace 'G'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(7,15): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(8,9): error TS2304: Cannot find name 'K'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(8,11): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(11,16): error TS2304: Cannot find name 'E'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(11,18): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(14,16): error TS2304: Cannot find name 'F'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(14,18): error TS2304: Cannot find name 'T'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts (9 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts (18 errors) ==== class C extends A implements B { ~ !!! error TS2304: Cannot find name 'A'. + ~ +!!! error TS2304: Cannot find name 'T'. ~ !!! error TS2304: Cannot find name 'B'. + ~ +!!! error TS2304: Cannot find name 'T'. } var v1: C; ~~~~ !!! error TS2315: Type 'C' is not generic. + ~ +!!! error TS2304: Cannot find name 'T'. var v2: D = null; ~ !!! error TS2304: Cannot find name 'D'. + ~ +!!! error TS2304: Cannot find name 'T'. var v3: E.F; ~ !!! error TS2503: Cannot find namespace 'E'. + ~ +!!! error TS2304: Cannot find name 'T'. var v3: G.H.I; ~ !!! error TS2503: Cannot find namespace 'G'. + ~ +!!! error TS2304: Cannot find name 'T'. var v6: K[]; ~ !!! error TS2304: Cannot find name 'K'. + ~ +!!! error TS2304: Cannot find name 'T'. function f1(a: E) { ~ !!! error TS2304: Cannot find name 'E'. + ~ +!!! error TS2304: Cannot find name 'T'. } function f2(): F { ~ !!! error TS2304: Cannot find name 'F'. + ~ +!!! error TS2304: Cannot find name 'T'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt b/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt index f686b56bf89..4fa6016feb7 100644 --- a/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt +++ b/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt @@ -1,47 +1,182 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,17): error TS2304: Cannot find name 'A'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,19): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,21): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,25): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,27): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,29): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,45): error TS2304: Cannot find name 'B'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,47): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,49): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,53): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,55): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,57): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(4,9): error TS2315: Type 'C' is not generic. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(4,11): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(4,13): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(4,17): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(4,19): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(4,21): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(5,9): error TS2304: Cannot find name 'D'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(5,11): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(5,13): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(5,17): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(5,19): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(5,21): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,9): error TS2503: Cannot find namespace 'E'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,13): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,15): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,19): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,21): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,23): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,9): error TS2503: Cannot find namespace 'G'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,15): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,17): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,21): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,23): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,25): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(8,9): error TS2304: Cannot find name 'K'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(8,11): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(8,13): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(8,17): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(8,19): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(8,21): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(11,16): error TS2304: Cannot find name 'E'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(11,18): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(11,20): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(11,24): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(11,26): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(11,28): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,16): error TS2304: Cannot find name 'F'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,18): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,20): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,24): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,26): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,28): error TS2304: Cannot find name 'T'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts (9 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts (54 errors) ==== class C extends A, Y>> implements B, Y>> { ~ !!! error TS2304: Cannot find name 'A'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. ~ !!! error TS2304: Cannot find name 'B'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. } var v1: C, Y>>; ~~~~~~~~~~~~~~~~ !!! error TS2315: Type 'C' is not generic. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. var v2: D, Y>> = null; ~ !!! error TS2304: Cannot find name 'D'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. var v3: E.F, Y>>; ~ !!! error TS2503: Cannot find namespace 'E'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. var v4: G.H.I, Y>>; ~ !!! error TS2503: Cannot find namespace 'G'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. var v6: K, Y>>[]; ~ !!! error TS2304: Cannot find name 'K'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. function f1(a: E, Y>>) { ~ !!! error TS2304: Cannot find name 'E'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. } function f2(): F, Y>> { ~ !!! error TS2304: Cannot find name 'F'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericsInVariableDeclaration1.errors.txt b/tests/baselines/reference/parserGenericsInVariableDeclaration1.errors.txt index 42f013cb250..6345f1ce34e 100644 --- a/tests/baselines/reference/parserGenericsInVariableDeclaration1.errors.txt +++ b/tests/baselines/reference/parserGenericsInVariableDeclaration1.errors.txt @@ -1,29 +1,65 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(1,9): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(1,13): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(2,9): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(2,13): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(4,9): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(4,13): error TS2304: Cannot find name 'Bar'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(4,17): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(5,9): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(5,13): error TS2304: Cannot find name 'Bar'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(5,17): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(7,9): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(7,13): error TS2304: Cannot find name 'Bar'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(7,17): error TS2304: Cannot find name 'Quux'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(7,22): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(8,9): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(8,13): error TS2304: Cannot find name 'Bar'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(8,17): error TS2304: Cannot find name 'Quux'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(8,22): error TS2304: Cannot find name 'T'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts (6 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts (18 errors) ==== var v : Foo = 1; ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'T'. var v : Foo= 1; ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'T'. var v : Foo> = 1; ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~~~ +!!! error TS2304: Cannot find name 'Bar'. + ~ +!!! error TS2304: Cannot find name 'T'. var v : Foo>= 1; ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~~~ +!!! error TS2304: Cannot find name 'Bar'. + ~ +!!! error TS2304: Cannot find name 'T'. var v : Foo>> = 1; ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~~~ +!!! error TS2304: Cannot find name 'Bar'. + ~~~~ +!!! error TS2304: Cannot find name 'Quux'. + ~ +!!! error TS2304: Cannot find name 'T'. var v : Foo>>= 1; ~~~ -!!! error TS2304: Cannot find name 'Foo'. \ No newline at end of file +!!! error TS2304: Cannot find name 'Foo'. + ~~~ +!!! error TS2304: Cannot find name 'Bar'. + ~~~~ +!!! error TS2304: Cannot find name 'Quux'. + ~ +!!! error TS2304: Cannot find name 'T'. \ No newline at end of file diff --git a/tests/baselines/reference/parserMemberAccessAfterPostfixExpression1.errors.txt b/tests/baselines/reference/parserMemberAccessAfterPostfixExpression1.errors.txt index 6af3f2843f6..6c2a0562a7c 100644 --- a/tests/baselines/reference/parserMemberAccessAfterPostfixExpression1.errors.txt +++ b/tests/baselines/reference/parserMemberAccessAfterPostfixExpression1.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/parser/ecmascript5/Expressions/parserMemberAccessAfterPostfixExpression1.ts(1,1): error TS2304: Cannot find name 'a'. tests/cases/conformance/parser/ecmascript5/Expressions/parserMemberAccessAfterPostfixExpression1.ts(1,4): error TS1005: ';' expected. -tests/cases/conformance/parser/ecmascript5/Expressions/parserMemberAccessAfterPostfixExpression1.ts(1,5): error TS2304: Cannot find name 'toString'. +tests/cases/conformance/parser/ecmascript5/Expressions/parserMemberAccessAfterPostfixExpression1.ts(1,5): error TS2552: Cannot find name 'toString'. Did you mean 'String'? ==== tests/cases/conformance/parser/ecmascript5/Expressions/parserMemberAccessAfterPostfixExpression1.ts (3 errors) ==== @@ -10,4 +10,4 @@ tests/cases/conformance/parser/ecmascript5/Expressions/parserMemberAccessAfterPo ~ !!! error TS1005: ';' expected. ~~~~~~~~ -!!! error TS2304: Cannot find name 'toString'. \ No newline at end of file +!!! error TS2552: Cannot find name 'toString'. Did you mean 'String'? \ No newline at end of file diff --git a/tests/baselines/reference/parserMemberAccessExpression1.errors.txt b/tests/baselines/reference/parserMemberAccessExpression1.errors.txt index 2006f5ac6d6..4e3e41770fe 100644 --- a/tests/baselines/reference/parserMemberAccessExpression1.errors.txt +++ b/tests/baselines/reference/parserMemberAccessExpression1.errors.txt @@ -1,25 +1,36 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(1,1): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(1,5): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(2,1): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(2,9): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(3,1): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(3,5): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(3,7): error TS1005: '(' expected. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(3,8): error TS2304: Cannot find name 'Bar'. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(3,13): error TS1005: ')' expected. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(4,1): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(4,5): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(4,7): error TS1005: '(' expected. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(4,8): error TS2304: Cannot find name 'Bar'. +tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(4,12): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(4,16): error TS1005: ')' expected. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts (10 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts (15 errors) ==== Foo(); ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'T'. Foo.Bar(); ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'T'. Foo.Bar(); ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'T'. ~ !!! error TS1005: '(' expected. ~~~ @@ -29,10 +40,14 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression Foo.Bar(); ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'T'. ~ !!! error TS1005: '(' expected. ~~~ !!! error TS2304: Cannot find name 'Bar'. + ~ +!!! error TS2304: Cannot find name 'T'. ~ !!! error TS1005: ')' expected. \ No newline at end of file diff --git a/tests/baselines/reference/parserMissingLambdaOpenBrace1.errors.txt b/tests/baselines/reference/parserMissingLambdaOpenBrace1.errors.txt index d39986c9c01..728295b76cb 100644 --- a/tests/baselines/reference/parserMissingLambdaOpenBrace1.errors.txt +++ b/tests/baselines/reference/parserMissingLambdaOpenBrace1.errors.txt @@ -1,17 +1,23 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(2,19): error TS2304: Cannot find name 'Iterator'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(2,28): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(2,42): error TS2304: Cannot find name 'Query'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(2,48): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(3,16): error TS2304: Cannot find name 'fromDoWhile'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(4,13): error TS1005: '{' expected. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(5,25): error TS2339: Property 'doWhile' does not exist on type 'C'. -==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts (5 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts (7 errors) ==== class C { where(filter: Iterator): Query { ~~~~~~~~ !!! error TS2304: Cannot find name 'Iterator'. + ~ +!!! error TS2304: Cannot find name 'T'. ~~~~~ !!! error TS2304: Cannot find name 'Query'. + ~ +!!! error TS2304: Cannot find name 'T'. return fromDoWhile(test => ~~~~~~~~~~~ !!! error TS2304: Cannot find name 'fromDoWhile'. diff --git a/tests/baselines/reference/parserNoASIOnCallAfterFunctionExpression1.errors.txt b/tests/baselines/reference/parserNoASIOnCallAfterFunctionExpression1.errors.txt index 7fc9396ac28..36bd5b08e19 100644 --- a/tests/baselines/reference/parserNoASIOnCallAfterFunctionExpression1.errors.txt +++ b/tests/baselines/reference/parserNoASIOnCallAfterFunctionExpression1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserNoASIOnCallAfterFunctionExpression1.ts(1,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/parser/ecmascript5/parserNoASIOnCallAfterFunctionExpression1.ts(1,9): error TS2554: Expected 0 arguments, but got 1. tests/cases/conformance/parser/ecmascript5/parserNoASIOnCallAfterFunctionExpression1.ts(2,7): error TS2304: Cannot find name 'window'. @@ -7,7 +7,7 @@ tests/cases/conformance/parser/ecmascript5/parserNoASIOnCallAfterFunctionExpress ~~~~~~~~~~~~~~~ (window).foo; ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 arguments, but got 1. ~~~~~~ !!! error TS2304: Cannot find name 'window'. \ No newline at end of file diff --git a/tests/baselines/reference/parserRealSource1.errors.txt b/tests/baselines/reference/parserRealSource1.errors.txt index 23d1a1d744a..696eff552a1 100644 --- a/tests/baselines/reference/parserRealSource1.errors.txt +++ b/tests/baselines/reference/parserRealSource1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource1.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource1.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. ==== tests/cases/conformance/parser/ecmascript5/parserRealSource1.ts (1 errors) ==== @@ -6,7 +6,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource1.ts(4,1): error TS60 // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource1.js b/tests/baselines/reference/parserRealSource1.js index d26e749a667..e41cb2a4b3f 100644 --- a/tests/baselines/reference/parserRealSource1.js +++ b/tests/baselines/reference/parserRealSource1.js @@ -247,28 +247,28 @@ var TypeScript; var addChar = function (index) { var ch = value.charCodeAt(index); switch (ch) { - case 0x09: + case 0x09:// tab result += "\\t"; break; - case 0x0a: + case 0x0a:// line feed result += "\\n"; break; - case 0x0b: + case 0x0b:// vertical tab result += "\\v"; break; - case 0x0c: + case 0x0c:// form feed result += "\\f"; break; - case 0x0d: + case 0x0d:// carriage return result += "\\r"; break; - case 0x22: + case 0x22:// double quote result += "\\\""; break; - case 0x27: + case 0x27:// single quote result += "\\\'"; break; - case 0x5c: + case 0x5c:// Backslash result += "\\"; break; default: diff --git a/tests/baselines/reference/parserRealSource10.errors.txt b/tests/baselines/reference/parserRealSource10.errors.txt index ae48cd79b51..6fd27b8351e 100644 --- a/tests/baselines/reference/parserRealSource10.errors.txt +++ b/tests/baselines/reference/parserRealSource10.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(127,33): error TS2449: Class 'TokenInfo' used before its declaration. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(127,42): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(128,36): error TS2304: Cannot find name 'string'. +tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(128,36): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(128,42): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(129,41): error TS2304: Cannot find name 'number'. +tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(129,41): error TS2693: 'number' only refers to a type, but is being used as a value here. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(129,47): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(130,35): error TS2304: Cannot find name 'boolean'. +tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(130,35): error TS2693: 'boolean' only refers to a type, but is being used as a value here. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(130,42): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(179,54): error TS2304: Cannot find name 'ErrorRecoverySet'. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(184,28): error TS2304: Cannot find name 'ErrorRecoverySet'. @@ -348,7 +348,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(449,40): error // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { @@ -479,17 +479,17 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(449,40): error !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. export var nodeTypeTable = new string[]; ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. export var nodeTypeToTokTable = new number[]; ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. export var noRegexTable = new boolean[]; ~~~~~~~ -!!! error TS2304: Cannot find name 'boolean'. +!!! error TS2693: 'boolean' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. diff --git a/tests/baselines/reference/parserRealSource11.errors.txt b/tests/baselines/reference/parserRealSource11.errors.txt index efae0f962fd..26cb07614a5 100644 --- a/tests/baselines/reference/parserRealSource11.errors.txt +++ b/tests/baselines/reference/parserRealSource11.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(13,22): error TS2304: Cannot find name 'Type'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(14,24): error TS2304: Cannot find name 'ASTFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(17,38): error TS2304: Cannot find name 'CompilerDiagnostics'. @@ -46,7 +46,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(199,42): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(219,33): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(231,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(231,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(233,52): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(233,52): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(237,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(251,21): error TS2304: Cannot find name 'Symbol'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(268,19): error TS2304: Cannot find name 'NodeType'. @@ -85,27 +85,27 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(427,22): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(441,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(441,48): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(445,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(446,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(446,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(449,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(451,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(451,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(453,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(454,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(454,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(457,22): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(460,22): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(463,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(465,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(465,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(467,22): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(469,50): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(472,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(472,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(474,22): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(476,50): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(479,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(479,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(481,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(483,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(483,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(485,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(487,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(487,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(489,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(491,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(491,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(494,22): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(496,58): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(498,22): error TS2304: Cannot find name 'NodeType'. @@ -522,7 +522,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { @@ -848,7 +848,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.recordSourceMappingStart(this); emitter.emitJavascriptList(this, null, TokenID.Semicolon, startLine, false, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.recordSourceMappingEnd(this); } @@ -1139,7 +1139,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error !!! error TS2304: Cannot find name 'NodeType'. emitter.emitJavascript(this.operand, TokenID.PlusPlus, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput("++"); break; case NodeType.LogNot: @@ -1148,14 +1148,14 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("!"); emitter.emitJavascript(this.operand, TokenID.Exclamation, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.DecPost: ~~~~~~~~ !!! error TS2304: Cannot find name 'NodeType'. emitter.emitJavascript(this.operand, TokenID.MinusMinus, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput("--"); break; case NodeType.ObjectLit: @@ -1174,7 +1174,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("~"); emitter.emitJavascript(this.operand, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.Neg: ~~~~~~~~ @@ -1187,7 +1187,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error } emitter.emitJavascript(this.operand, TokenID.Minus, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.Pos: ~~~~~~~~ @@ -1200,7 +1200,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error } emitter.emitJavascript(this.operand, TokenID.Plus, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.IncPre: ~~~~~~~~ @@ -1208,7 +1208,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("++"); emitter.emitJavascript(this.operand, TokenID.PlusPlus, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.DecPre: ~~~~~~~~ @@ -1216,7 +1216,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("--"); emitter.emitJavascript(this.operand, TokenID.MinusMinus, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.Throw: ~~~~~~~~ @@ -1224,7 +1224,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("throw "); emitter.emitJavascript(this.operand, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput(";"); break; case NodeType.Typeof: diff --git a/tests/baselines/reference/parserRealSource12.errors.txt b/tests/baselines/reference/parserRealSource12.errors.txt index 22fb209d80c..a1e959d38cc 100644 --- a/tests/baselines/reference/parserRealSource12.errors.txt +++ b/tests/baselines/reference/parserRealSource12.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource12.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource12.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource12.ts(8,19): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource12.ts(8,32): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource12.ts(8,38): error TS2304: Cannot find name 'AST'. @@ -214,7 +214,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource12.ts(524,30): error // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource13.errors.txt b/tests/baselines/reference/parserRealSource13.errors.txt index 6ddc41ed610..35bdd1cbb62 100644 --- a/tests/baselines/reference/parserRealSource13.errors.txt +++ b/tests/baselines/reference/parserRealSource13.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(8,35): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(9,39): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(10,34): error TS2304: Cannot find name 'AST'. @@ -113,7 +113,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(123,26): error tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(123,39): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(128,33): error TS2339: Property 'getAstWalkerFactory' does not exist on type 'typeof TypeScript'. tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(132,51): error TS2304: Cannot find name 'AST'. -tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(135,36): error TS2304: Cannot find name 'NodeType'. +tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(135,36): error TS2552: Cannot find name 'NodeType'. Did you mean 'nodeType'? ==== tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts (116 errors) ==== @@ -121,7 +121,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(135,36): error // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript.AstWalkerWithDetailCallback { @@ -483,7 +483,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(135,36): error var nodeType = ast.nodeType; var callbackString = (NodeType)._map[nodeType] + "Callback"; ~~~~~~~~ -!!! error TS2304: Cannot find name 'NodeType'. +!!! error TS2552: Cannot find name 'NodeType'. Did you mean 'nodeType'? if (callback[callbackString]) { return callback[callbackString](pre, ast); } diff --git a/tests/baselines/reference/parserRealSource14.errors.txt b/tests/baselines/reference/parserRealSource14.errors.txt index 8682b1e6557..2e1fe6e7b56 100644 --- a/tests/baselines/reference/parserRealSource14.errors.txt +++ b/tests/baselines/reference/parserRealSource14.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource14.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource14.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource14.ts(24,33): error TS2694: Namespace 'TypeScript' has no exported member 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource14.ts(38,34): error TS2694: Namespace 'TypeScript' has no exported member 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource14.ts(48,37): error TS2694: Namespace 'TypeScript' has no exported member 'AST'. @@ -165,7 +165,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource14.ts(572,20): error // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource2.errors.txt b/tests/baselines/reference/parserRealSource2.errors.txt index 42fcff36c70..8e0e1f13b15 100644 --- a/tests/baselines/reference/parserRealSource2.errors.txt +++ b/tests/baselines/reference/parserRealSource2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource2.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource2.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. ==== tests/cases/conformance/parser/ecmascript5/parserRealSource2.ts (1 errors) ==== @@ -6,7 +6,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource2.ts(4,1): error TS60 // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource3.errors.txt b/tests/baselines/reference/parserRealSource3.errors.txt index 5b00994052b..1ee68afa81a 100644 --- a/tests/baselines/reference/parserRealSource3.errors.txt +++ b/tests/baselines/reference/parserRealSource3.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource3.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource3.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. ==== tests/cases/conformance/parser/ecmascript5/parserRealSource3.ts (1 errors) ==== @@ -6,7 +6,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource3.ts(4,1): error TS60 // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource4.errors.txt b/tests/baselines/reference/parserRealSource4.errors.txt index 9722a5b670d..5fe47b7a8e3 100644 --- a/tests/baselines/reference/parserRealSource4.errors.txt +++ b/tests/baselines/reference/parserRealSource4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource4.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource4.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource4.ts(195,37): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. @@ -7,7 +7,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource4.ts(195,37): error T // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource5.errors.txt b/tests/baselines/reference/parserRealSource5.errors.txt index 7dc9b5942d5..fd2932df0d9 100644 --- a/tests/baselines/reference/parserRealSource5.errors.txt +++ b/tests/baselines/reference/parserRealSource5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource5.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource5.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource5.ts(14,38): error TS2304: Cannot find name 'ITextWriter'. tests/cases/conformance/parser/ecmascript5/parserRealSource5.ts(14,66): error TS2304: Cannot find name 'Parser'. tests/cases/conformance/parser/ecmascript5/parserRealSource5.ts(27,17): error TS2304: Cannot find name 'CompilerDiagnostics'. @@ -15,7 +15,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource5.ts(61,65): error TS // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource6.errors.txt b/tests/baselines/reference/parserRealSource6.errors.txt index aa6a9f41392..75c0ae8c139 100644 --- a/tests/baselines/reference/parserRealSource6.errors.txt +++ b/tests/baselines/reference/parserRealSource6.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource6.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource6.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource6.ts(8,24): error TS2304: Cannot find name 'Script'. tests/cases/conformance/parser/ecmascript5/parserRealSource6.ts(10,41): error TS2304: Cannot find name 'ScopeChain'. tests/cases/conformance/parser/ecmascript5/parserRealSource6.ts(10,69): error TS2304: Cannot find name 'TypeChecker'. @@ -66,7 +66,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource6.ts(215,20): error T // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource7.errors.txt b/tests/baselines/reference/parserRealSource7.errors.txt index a3635dabc48..f98dd31dba9 100644 --- a/tests/baselines/reference/parserRealSource7.errors.txt +++ b/tests/baselines/reference/parserRealSource7.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(12,38): error TS2304: Cannot find name 'ASTList'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(12,62): error TS2304: Cannot find name 'TypeLink'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(16,37): error TS2304: Cannot find name 'TypeLink'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(16,37): error TS2552: Cannot find name 'TypeLink'. Did you mean 'typeLink'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(16,45): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(21,36): error TS2304: Cannot find name 'TypeLink'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(21,36): error TS2552: Cannot find name 'TypeLink'. Did you mean 'typeLink'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(29,29): error TS2304: Cannot find name 'Type'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(29,45): error TS2304: Cannot find name 'TypeDeclaration'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(34,43): error TS2304: Cannot find name 'Type'. @@ -11,11 +11,11 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(34,54): error TS tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(34,68): error TS2304: Cannot find name 'TypeCollectionContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(35,25): error TS2304: Cannot find name 'ValueLocation'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(36,30): error TS2304: Cannot find name 'TypeLink'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(41,17): error TS2304: Cannot find name 'FieldSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(41,17): error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(43,31): error TS2304: Cannot find name 'SymbolFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(43,54): error TS2304: Cannot find name 'SymbolFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(49,58): error TS2304: Cannot find name 'Type'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(50,29): error TS2304: Cannot find name 'Signature'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(50,29): error TS2552: Cannot find name 'Signature'. Did you mean 'signature'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(51,36): error TS2304: Cannot find name 'TypeLink'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(55,30): error TS2304: Cannot find name 'SignatureGroup'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(59,66): error TS2304: Cannot find name 'Type'. @@ -46,7 +46,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(154,27): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(155,26): error TS2304: Cannot find name 'hasFlag'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(155,55): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(165,28): error TS2304: Cannot find name 'ModuleType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(169,26): error TS2304: Cannot find name 'TypeSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(169,26): error TS2552: Cannot find name 'TypeSymbol'. Did you mean 'typeSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(186,48): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(186,61): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(186,75): error TS2304: Cannot find name 'TypeCollectionContext'. @@ -81,8 +81,8 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(212,46): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(212,64): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(212,88): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(212,111): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(216,30): error TS2304: Cannot find name 'TypeSymbol'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(231,72): error TS2304: Cannot find name 'NodeType'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(216,30): error TS2552: Cannot find name 'TypeSymbol'. Did you mean 'typeSymbol'? +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(231,72): error TS2552: Cannot find name 'NodeType'. Did you mean 'modType'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(234,27): error TS2304: Cannot find name 'TypeSymbol'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(238,80): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(239,37): error TS2304: Cannot find name 'ScopedMembers'. @@ -142,7 +142,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(349,47): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(349,65): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(349,89): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(349,112): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(350,30): error TS2304: Cannot find name 'TypeSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(350,30): error TS2552: Cannot find name 'TypeSymbol'. Did you mean 'typeSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(360,37): error TS2304: Cannot find name 'SymbolFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(364,37): error TS2304: Cannot find name 'SymbolFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(368,37): error TS2304: Cannot find name 'SymbolFlags'. @@ -196,7 +196,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(476,57): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(477,29): error TS2304: Cannot find name 'ValueLocation'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(478,29): error TS2304: Cannot find name 'hasFlag'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(478,55): error TS2304: Cannot find name 'VarFlags'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(480,21): error TS2304: Cannot find name 'FieldSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(480,21): error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(482,34): error TS2304: Cannot find name 'hasFlag'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(482,60): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(492,30): error TS2304: Cannot find name 'getTypeLink'. @@ -218,7 +218,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(507,26): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(507,52): error TS2304: Cannot find name 'ASTFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(518,22): error TS2304: Cannot find name 'FieldSymbol'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(531,29): error TS2304: Cannot find name 'ValueLocation'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(533,21): error TS2304: Cannot find name 'FieldSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(533,21): error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(535,53): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(535,75): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(539,38): error TS2304: Cannot find name 'SymbolFlags'. @@ -308,7 +308,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { @@ -327,7 +327,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T if (baseTypeLinks == null) { baseTypeLinks = new TypeLink[]; ~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeLink'. +!!! error TS2552: Cannot find name 'TypeLink'. Did you mean 'typeLink'? ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. } @@ -336,7 +336,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T var name = baseExpr; var typeLink = new TypeLink(); ~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeLink'. +!!! error TS2552: Cannot find name 'TypeLink'. Did you mean 'typeLink'? typeLink.ast = name; baseTypeLinks[baseTypeLinks.length] = typeLink; } @@ -372,7 +372,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T var fieldSymbol = new FieldSymbol("prototype", ast.minChar, ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'FieldSymbol'. +!!! error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? context.checker.locationInfo.unitIndex, true, field); fieldSymbol.flags |= (SymbolFlags.Property | SymbolFlags.BuiltIn); ~~~~~~~~~~~ @@ -389,7 +389,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T !!! error TS2304: Cannot find name 'Type'. var signature = new Signature(); ~~~~~~~~~ -!!! error TS2304: Cannot find name 'Signature'. +!!! error TS2552: Cannot find name 'Signature'. Did you mean 'signature'? signature.returnType = new TypeLink(); ~~~~~~~~ !!! error TS2304: Cannot find name 'TypeLink'. @@ -570,7 +570,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T typeSymbol = new TypeSymbol(importDecl.id.text, importDecl.minChar, ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeSymbol'. +!!! error TS2552: Cannot find name 'TypeSymbol'. Did you mean 'typeSymbol'? context.checker.locationInfo.unitIndex, modType); typeSymbol.aliasLink = importDecl; @@ -687,7 +687,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T typeSymbol = new TypeSymbol(modName, moduleDecl.minChar, ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeSymbol'. +!!! error TS2552: Cannot find name 'TypeSymbol'. Did you mean 'typeSymbol'? context.checker.locationInfo.unitIndex, modType); if (context.scopeChain.moduleDecl) { @@ -704,7 +704,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T else { if (symbol && symbol.declAST && symbol.declAST.nodeType != NodeType.ModuleDeclaration) { ~~~~~~~~ -!!! error TS2304: Cannot find name 'NodeType'. +!!! error TS2552: Cannot find name 'NodeType'. Did you mean 'modType'? context.checker.errorReporter.simpleError(moduleDecl, "Conflicting symbol name for module '" + modName + "'"); } typeSymbol = symbol; @@ -943,7 +943,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T !!! error TS2304: Cannot find name 'StringHashTable'. typeSymbol = new TypeSymbol(className, classDecl.minChar, ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeSymbol'. +!!! error TS2552: Cannot find name 'TypeSymbol'. Did you mean 'typeSymbol'? context.checker.locationInfo.unitIndex, classType); typeSymbol.declAST = classDecl; typeSymbol.instanceType = instanceType; @@ -1181,7 +1181,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T var fieldSymbol = new FieldSymbol(argDecl.id.text, argDecl.minChar, ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'FieldSymbol'. +!!! error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? context.checker.locationInfo.unitIndex, !hasFlag(argDecl.varFlags, VarFlags.Readonly), ~~~~~~~ @@ -1278,7 +1278,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T var fieldSymbol = new FieldSymbol(varDecl.id.text, varDecl.minChar, ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'FieldSymbol'. +!!! error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? context.checker.locationInfo.unitIndex, (varDecl.varFlags & VarFlags.Readonly) == VarFlags.None, ~~~~~~~~ diff --git a/tests/baselines/reference/parserRealSource8.errors.txt b/tests/baselines/reference/parserRealSource8.errors.txt index 6249d3fd991..a7a2b968baf 100644 --- a/tests/baselines/reference/parserRealSource8.errors.txt +++ b/tests/baselines/reference/parserRealSource8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(9,41): error TS2304: Cannot find name 'ScopeChain'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(10,39): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(11,43): error TS2304: Cannot find name 'ModuleDeclaration'. @@ -47,7 +47,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(160,52): error T tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(160,76): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(160,99): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(162,28): error TS2304: Cannot find name 'Type'. -tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(163,30): error TS2304: Cannot find name 'WithSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(163,30): error TS2552: Cannot find name 'WithSymbol'. Did you mean 'withSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(170,40): error TS2339: Property 'SymbolScopeBuilder' does not exist on type 'typeof TypeScript'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(176,50): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(177,25): error TS2304: Cannot find name 'FuncDecl'. @@ -139,7 +139,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(454,35): error T // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { @@ -397,7 +397,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(454,35): error T !!! error TS2304: Cannot find name 'Type'. var withSymbol = new WithSymbol(withStmt.minChar, context.typeFlow.checker.locationInfo.unitIndex, withType); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'WithSymbol'. +!!! error TS2552: Cannot find name 'WithSymbol'. Did you mean 'withSymbol'? withType.members = members; withType.ambientMembers = ambientMembers; withType.symbol = withSymbol; diff --git a/tests/baselines/reference/parserRealSource9.errors.txt b/tests/baselines/reference/parserRealSource9.errors.txt index caa142db60e..6533fdbcfc4 100644 --- a/tests/baselines/reference/parserRealSource9.errors.txt +++ b/tests/baselines/reference/parserRealSource9.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource9.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource9.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource9.ts(8,38): error TS2304: Cannot find name 'TypeChecker'. tests/cases/conformance/parser/ecmascript5/parserRealSource9.ts(9,48): error TS2304: Cannot find name 'TypeLink'. tests/cases/conformance/parser/ecmascript5/parserRealSource9.ts(9,67): error TS2304: Cannot find name 'SymbolScope'. @@ -38,7 +38,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource9.ts(200,48): error T // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserS7.2_A1.5_T2.errors.txt b/tests/baselines/reference/parserS7.2_A1.5_T2.errors.txt index c86756b4ab1..3d35062bfc2 100644 --- a/tests/baselines/reference/parserS7.2_A1.5_T2.errors.txt +++ b/tests/baselines/reference/parserS7.2_A1.5_T2.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts(14,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts(20,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts(14,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts(20,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? ==== tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts (2 errors) ==== @@ -18,7 +18,7 @@ tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts(20,3): error TS if (x !== 1) { $ERROR('#1: eval("\\u00A0var x\\u00A0= 1\\u00A0"); x === 1. Actual: ' + (x)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } //CHECK#2 @@ -26,7 +26,7 @@ tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts(20,3): error TS if (x !== 1) { $ERROR('#2:  var x = 1 ; x === 1. Actual: ' + (x)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } diff --git a/tests/baselines/reference/parserS7.3_A1.1_T2.errors.txt b/tests/baselines/reference/parserS7.3_A1.1_T2.errors.txt index e999066aa41..d4131cc799d 100644 --- a/tests/baselines/reference/parserS7.3_A1.1_T2.errors.txt +++ b/tests/baselines/reference/parserS7.3_A1.1_T2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserS7.3_A1.1_T2.ts(17,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.3_A1.1_T2.ts(17,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? ==== tests/cases/conformance/parser/ecmascript5/parserS7.3_A1.1_T2.ts (1 errors) ==== @@ -20,7 +20,7 @@ tests/cases/conformance/parser/ecmascript5/parserS7.3_A1.1_T2.ts(17,3): error TS if (x !== 1) { $ERROR('#1: var\\nx\\n=\\n1\\n; x === 1. Actual: ' + (x)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } \ No newline at end of file diff --git a/tests/baselines/reference/parserS7.6_A4.2_T1.errors.txt b/tests/baselines/reference/parserS7.6_A4.2_T1.errors.txt index 153fb96ddac..53865fd69ab 100644 --- a/tests/baselines/reference/parserS7.6_A4.2_T1.errors.txt +++ b/tests/baselines/reference/parserS7.6_A4.2_T1.errors.txt @@ -1,13 +1,13 @@ -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(14,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(18,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(22,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(26,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(30,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(34,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(38,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(42,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(46,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(50,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(14,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(18,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(22,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(26,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(30,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(34,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(38,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(42,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(46,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(50,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(54,3): error TS2304: Cannot find name '$ERROR'. tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(58,3): error TS2304: Cannot find name '$ERROR'. tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(62,3): error TS2304: Cannot find name '$ERROR'. @@ -49,61 +49,61 @@ tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(142,3): error T if (А !== 1) { $ERROR('#А'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0411 = 1; if (Б !== 1) { $ERROR('#Б'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0412 = 1; if (В !== 1) { $ERROR('#В'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0413 = 1; if (Г !== 1) { $ERROR('#Г'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0414 = 1; if (Д !== 1) { $ERROR('#Д'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0415 = 1; if (Е !== 1) { $ERROR('#Е'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0416 = 1; if (Ж !== 1) { $ERROR('#Ж'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0417 = 1; if (З !== 1) { $ERROR('#З'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0418 = 1; if (И !== 1) { $ERROR('#И'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0419 = 1; if (Й !== 1) { $ERROR('#Й'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041A = 1; if (К !== 1) { diff --git a/tests/baselines/reference/parserSkippedTokens16.errors.txt b/tests/baselines/reference/parserSkippedTokens16.errors.txt index fc3565e9786..3f0321ed00c 100644 --- a/tests/baselines/reference/parserSkippedTokens16.errors.txt +++ b/tests/baselines/reference/parserSkippedTokens16.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(1,1): error TS2304: Cannot find name 'foo'. +tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(1,1): error TS2552: Cannot find name 'foo'. Did you mean 'Foo'? tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(1,6): error TS1005: ';' expected. tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(1,8): error TS2304: Cannot find name 'Bar'. tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(1,12): error TS1005: ';' expected. @@ -11,7 +11,7 @@ tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.t ==== tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts (8 errors) ==== foo(): Bar { } ~~~ -!!! error TS2304: Cannot find name 'foo'. +!!! error TS2552: Cannot find name 'foo'. Did you mean 'Foo'? ~ !!! error TS1005: ';' expected. ~~~ diff --git a/tests/baselines/reference/parserSkippedTokens20.errors.txt b/tests/baselines/reference/parserSkippedTokens20.errors.txt index 774443d4d9a..d32f25a26b3 100644 --- a/tests/baselines/reference/parserSkippedTokens20.errors.txt +++ b/tests/baselines/reference/parserSkippedTokens20.errors.txt @@ -1,10 +1,13 @@ tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens20.ts(1,8): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens20.ts(1,10): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens20.ts(1,12): error TS1127: Invalid character. -==== tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens20.ts (2 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens20.ts (3 errors) ==== var v: X(0); @@ -10,5 +11,7 @@ tests/cases/conformance/parser/ecmascript5/SuperExpressions/parserSuperExpressio !!! error TS2335: 'super' can only be referenced in a derived class. ~ !!! error TS1034: 'super' must be followed by an argument list or member access. + ~ +!!! error TS2304: Cannot find name 'T'. } } \ No newline at end of file diff --git a/tests/baselines/reference/parserSuperExpression3.errors.txt b/tests/baselines/reference/parserSuperExpression3.errors.txt index 2fd81b29957..13faa304097 100644 --- a/tests/baselines/reference/parserSuperExpression3.errors.txt +++ b/tests/baselines/reference/parserSuperExpression3.errors.txt @@ -1,11 +1,14 @@ tests/cases/conformance/parser/ecmascript5/SuperExpressions/parserSuperExpression3.ts(3,10): error TS2339: Property 'super' does not exist on type 'C'. +tests/cases/conformance/parser/ecmascript5/SuperExpressions/parserSuperExpression3.ts(3,16): error TS2304: Cannot find name 'T'. -==== tests/cases/conformance/parser/ecmascript5/SuperExpressions/parserSuperExpression3.ts (1 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/SuperExpressions/parserSuperExpression3.ts (2 errors) ==== class C { M() { this.super(0); ~~~~~ !!! error TS2339: Property 'super' does not exist on type 'C'. + ~ +!!! error TS2304: Cannot find name 'T'. } } \ No newline at end of file diff --git a/tests/baselines/reference/parserSymbolIndexer5.errors.txt b/tests/baselines/reference/parserSymbolIndexer5.errors.txt index a8c19338e01..7906d08912c 100644 --- a/tests/baselines/reference/parserSymbolIndexer5.errors.txt +++ b/tests/baselines/reference/parserSymbolIndexer5.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(2,6): error TS2304: Cannot find name 's'. tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(2,7): error TS1005: ']' expected. -tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(2,9): error TS2304: Cannot find name 'symbol'. +tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(2,9): error TS2552: Cannot find name 'symbol'. Did you mean 'Symbol'? tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(2,15): error TS1005: ',' expected. tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(2,16): error TS1136: Property assignment expected. tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(3,1): error TS1005: ':' expected. @@ -14,7 +14,7 @@ tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(3,1): ~ !!! error TS1005: ']' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'symbol'. +!!! error TS2552: Cannot find name 'symbol'. Did you mean 'Symbol'? ~ !!! error TS1005: ',' expected. ~ diff --git a/tests/baselines/reference/parserUnicode1.errors.txt b/tests/baselines/reference/parserUnicode1.errors.txt index 6f56522c05c..d04e136a534 100644 --- a/tests/baselines/reference/parserUnicode1.errors.txt +++ b/tests/baselines/reference/parserUnicode1.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/parser/ecmascript5/parserUnicode1.ts(6,5): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserUnicode1.ts(10,5): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserUnicode1.ts(6,5): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserUnicode1.ts(10,5): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? ==== tests/cases/conformance/parser/ecmascript5/parserUnicode1.ts (2 errors) ==== @@ -10,12 +10,12 @@ tests/cases/conformance/parser/ecmascript5/parserUnicode1.ts(10,5): error TS2304 $ERROR('#6.1: var \\u0078x = 1; xx === 6. Actual: ' + (xx)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } } catch (e) { $ERROR('#6.2: var \\u0078x = 1; xx === 6. Actual: ' + (xx)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } \ No newline at end of file diff --git a/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt b/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt index a2be22d5ee0..e38a548f34c 100644 --- a/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt +++ b/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt @@ -4,12 +4,12 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGener tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,9): error TS2304: Cannot find name 'assign'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,16): error TS2304: Cannot find name 'context'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,23): error TS1005: ',' expected. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,25): error TS2304: Cannot find name 'any'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,25): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,30): error TS2304: Cannot find name 'value'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,35): error TS1005: ',' expected. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,37): error TS2304: Cannot find name 'any'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,37): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,41): error TS1005: ';' expected. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,43): error TS2304: Cannot find name 'any'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,43): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(8,23): error TS2304: Cannot find name 'IPromise'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(8,45): error TS2304: Cannot find name 'IPromise'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(8,54): error TS1005: '>' expected. @@ -33,17 +33,17 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGener ~ !!! error TS1005: ',' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. ~~~~~ !!! error TS2304: Cannot find name 'value'. ~ !!! error TS1005: ',' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. } interface IQService { diff --git a/tests/baselines/reference/parserharness.errors.txt b/tests/baselines/reference/parserharness.errors.txt index d3d0c4056a1..e7c83f0a058 100644 --- a/tests/baselines/reference/parserharness.errors.txt +++ b/tests/baselines/reference/parserharness.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(16,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/compiler/io.ts' not found. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(17,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/compiler/typescript.ts' not found. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(18,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/services/typescriptServices.ts' not found. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(19,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/RealWorld/diff.ts' not found. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(16,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/compiler/io.ts' not found. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(17,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/compiler/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(18,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/services/typescriptServices.ts' not found. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(19,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/RealWorld/diff.ts' not found. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(21,29): error TS2694: Namespace 'Harness' has no exported member 'Assert'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(25,17): error TS2304: Cannot find name 'IIO'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(41,12): error TS2304: Cannot find name 'ActiveXObject'. @@ -16,19 +16,19 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(691,50): e tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(716,47): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(721,62): error TS2304: Cannot find name 'ITextWriter'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(724,29): error TS2304: Cannot find name 'ITextWriter'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(754,53): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(754,53): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(764,56): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(765,37): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(767,47): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(776,13): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(776,42): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(765,37): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(767,47): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(776,13): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(776,42): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(781,23): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(794,49): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(795,49): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,53): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,89): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(794,49): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(795,49): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,53): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,89): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,115): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,145): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,145): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(988,43): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(999,40): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1041,43): error TS2503: Cannot find namespace 'TypeScript'. @@ -127,16 +127,16 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): // /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/compiler/io.ts' not found. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/compiler/typescript.ts' not found. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/services/typescriptServices.ts' not found. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/RealWorld/diff.ts' not found. declare var assert: Harness.Assert; @@ -902,7 +902,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): var libFolder: string = global['WScript'] ? TypeScript.filePath(global['WScript'].ScriptFullName) : (__dirname + '/'); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? export var libText = IO ? IO.readFile(libFolder + "lib.d.ts") : ''; var stdout = new EmitterIOHost(); @@ -917,11 +917,11 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): !!! error TS2503: Cannot find namespace 'TypeScript'. var compiler = c || new TypeScript.TypeScriptCompiler(stderr); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? compiler.parser.errorRecovery = true; compiler.settings.codeGenTarget = TypeScript.CodeGenTarget.ES5; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? compiler.settings.controlFlow = true; compiler.settings.controlFlowUseDef = true; if (Harness.usePull) { @@ -932,9 +932,9 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): compiler.parseEmitOption(stdout); TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? compiler.addUnit(Harness.Compiler.libText, "lib.d.ts", true); return compiler; } @@ -956,10 +956,10 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): // requires unit to already exist in the compiler compiler.pullUpdateUnit(new TypeScript.StringSourceText(""), filename, true); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? compiler.pullUpdateUnit(new TypeScript.StringSourceText(code), filename, true); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? } } else { @@ -1153,13 +1153,13 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): var script = compiler.scripts.members[m]; var enclosingScopeContext = TypeScript.findEnclosingScopeAt(new TypeScript.NullLogger(), script, new TypeScript.StringSourceText(code), 0, false); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? var entries = new TypeScript.ScopeTraversal(compiler).getScopeEntries(enclosingScopeContext); ~~~~~~~~~~ !!! error TS2304: Cannot find name 'TypeScript'. diff --git a/tests/baselines/reference/parserindenter.errors.txt b/tests/baselines/reference/parserindenter.errors.txt index 2f51281e7aa..371072a4622 100644 --- a/tests/baselines/reference/parserindenter.errors.txt +++ b/tests/baselines/reference/parserindenter.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(16,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/RealWorld/formatting.ts' not found. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(16,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/RealWorld/formatting.ts' not found. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(20,38): error TS2304: Cannot find name 'ILineIndenationResolver'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(22,33): error TS2304: Cannot find name 'IndentationBag'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(24,42): error TS2304: Cannot find name 'Dictionary_int_int'. @@ -145,7 +145,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(736,38): // /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/RealWorld/formatting.ts' not found. diff --git a/tests/baselines/reference/parserindenter.js b/tests/baselines/reference/parserindenter.js index 8beb2393748..17f71318940 100644 --- a/tests/baselines/reference/parserindenter.js +++ b/tests/baselines/reference/parserindenter.js @@ -912,20 +912,20 @@ var Formatting; Indenter.prototype.GetSpecialCaseIndentation = function (token, node) { var indentationInfo = null; switch (token.Token) { - case AuthorTokenKind.atkLCurly: + case AuthorTokenKind.atkLCurly:// { is not part of the tree indentationInfo = this.GetSpecialCaseIndentationForLCurly(node); return indentationInfo; case AuthorTokenKind.atkElse: // else is not part of the tree - case AuthorTokenKind.atkRBrack: + case AuthorTokenKind.atkRBrack:// ] is not part of the tree indentationInfo = node.GetNodeStartLineIndentation(this); return indentationInfo; - case AuthorTokenKind.atkRCurly: + case AuthorTokenKind.atkRCurly:// } is not part of the tree // if '}' is for a body-block, get indentation based on its parent. if (node.AuthorNode.Details.Kind == AuthorParseNodeKind.apnkBlock && node.AuthorNode.EdgeLabel == AuthorParseNodeEdge.apneBody) node = node.Parent; indentationInfo = node.GetNodeStartLineIndentation(this); return indentationInfo; - case AuthorTokenKind.atkWhile: + case AuthorTokenKind.atkWhile:// while (in do-while) is not part of the tree if (node.AuthorNode.Details.Kind == AuthorParseNodeKind.apnkDoWhile) { indentationInfo = node.GetNodeStartLineIndentation(this); return indentationInfo; diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.js b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.js new file mode 100644 index 00000000000..c54c0ba61ed --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.js @@ -0,0 +1,16 @@ +//// [tests/cases/compiler/pathMappingBasedModuleResolution_withExtensionInName.ts] //// + +//// [index.d.ts] +export const x: number; + +//// [index.d.ts] +export const y: number; + +//// [a.ts] +import { x } from "zone.js"; +import { y } from "zone.tsx"; + + +//// [a.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.symbols b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.symbols new file mode 100644 index 00000000000..440ef2d2942 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.symbols @@ -0,0 +1,15 @@ +=== /a.ts === +import { x } from "zone.js"; +>x : Symbol(x, Decl(a.ts, 0, 8)) + +import { y } from "zone.tsx"; +>y : Symbol(y, Decl(a.ts, 1, 8)) + +=== /foo/zone.js/index.d.ts === +export const x: number; +>x : Symbol(x, Decl(index.d.ts, 0, 12)) + +=== /foo/zone.tsx/index.d.ts === +export const y: number; +>y : Symbol(y, Decl(index.d.ts, 0, 12)) + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.trace.json new file mode 100644 index 00000000000..216442fb378 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.trace.json @@ -0,0 +1,38 @@ +[ + "======== Resolving module 'zone.js' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/', using this value to resolve non-relative module name 'zone.js'.", + "'paths' option is specified, looking for a pattern to match module name 'zone.js'.", + "Module name 'zone.js', matched pattern '*'.", + "Trying substitution 'foo/*', candidate module location: 'foo/zone.js'.", + "File '/foo/zone.js' does not exist.", + "Loading module as file / folder, candidate module location '/foo/zone.js', target file type 'TypeScript'.", + "File '/foo/zone.js.ts' does not exist.", + "File '/foo/zone.js.tsx' does not exist.", + "File '/foo/zone.js.d.ts' does not exist.", + "File name '/foo/zone.js' has a '.js' extension - stripping it.", + "File '/foo/zone.ts' does not exist.", + "File '/foo/zone.tsx' does not exist.", + "File '/foo/zone.d.ts' does not exist.", + "File '/foo/zone.js/package.json' does not exist.", + "File '/foo/zone.js/index.ts' does not exist.", + "File '/foo/zone.js/index.tsx' does not exist.", + "File '/foo/zone.js/index.d.ts' exist - use it as a name resolution result.", + "======== Module name 'zone.js' was successfully resolved to '/foo/zone.js/index.d.ts'. ========", + "======== Resolving module 'zone.tsx' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/', using this value to resolve non-relative module name 'zone.tsx'.", + "'paths' option is specified, looking for a pattern to match module name 'zone.tsx'.", + "Module name 'zone.tsx', matched pattern '*'.", + "Trying substitution 'foo/*', candidate module location: 'foo/zone.tsx'.", + "File '/foo/zone.tsx' does not exist.", + "Loading module as file / folder, candidate module location '/foo/zone.tsx', target file type 'TypeScript'.", + "File '/foo/zone.tsx.ts' does not exist.", + "File '/foo/zone.tsx.tsx' does not exist.", + "File '/foo/zone.tsx.d.ts' does not exist.", + "File '/foo/zone.tsx/package.json' does not exist.", + "File '/foo/zone.tsx/index.ts' does not exist.", + "File '/foo/zone.tsx/index.tsx' does not exist.", + "File '/foo/zone.tsx/index.d.ts' exist - use it as a name resolution result.", + "======== Module name 'zone.tsx' was successfully resolved to '/foo/zone.tsx/index.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.types b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.types new file mode 100644 index 00000000000..7fd8a2710c6 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.types @@ -0,0 +1,15 @@ +=== /a.ts === +import { x } from "zone.js"; +>x : number + +import { y } from "zone.tsx"; +>y : number + +=== /foo/zone.js/index.d.ts === +export const x: number; +>x : number + +=== /foo/zone.tsx/index.d.ts === +export const y: number; +>y : number + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.trace.json index 7561a47b1e7..803520f12fd 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.trace.json @@ -6,6 +6,7 @@ "Module name 'foo', matched pattern 'foo'.", "Trying substitution 'foo/foo.ts', candidate module location: 'foo/foo.ts'.", "File '/foo/foo.ts' does not exist.", + "Loading module as file / folder, candidate module location '/foo/foo.ts', target file type 'TypeScript'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", "Directory '/node_modules' does not exist, skipping all lookups in it.", "'baseUrl' option is set to '/', using this value to resolve non-relative module name 'foo'.", @@ -13,6 +14,7 @@ "Module name 'foo', matched pattern 'foo'.", "Trying substitution 'foo/foo.ts', candidate module location: 'foo/foo.ts'.", "File '/foo/foo.ts' does not exist.", + "Loading module as file / folder, candidate module location '/foo/foo.ts', target file type 'JavaScript'.", "Loading module 'foo' from 'node_modules' folder, target file type 'JavaScript'.", "Directory '/node_modules' does not exist, skipping all lookups in it.", "======== Module name 'foo' was not resolved. ========" diff --git a/tests/baselines/reference/primitiveTypeAssignment.errors.txt b/tests/baselines/reference/primitiveTypeAssignment.errors.txt index 3985a9acdc5..1800e1657e0 100644 --- a/tests/baselines/reference/primitiveTypeAssignment.errors.txt +++ b/tests/baselines/reference/primitiveTypeAssignment.errors.txt @@ -1,18 +1,18 @@ -tests/cases/compiler/primitiveTypeAssignment.ts(1,9): error TS2304: Cannot find name 'any'. -tests/cases/compiler/primitiveTypeAssignment.ts(3,9): error TS2304: Cannot find name 'number'. -tests/cases/compiler/primitiveTypeAssignment.ts(5,9): error TS2304: Cannot find name 'boolean'. +tests/cases/compiler/primitiveTypeAssignment.ts(1,9): error TS2693: 'any' only refers to a type, but is being used as a value here. +tests/cases/compiler/primitiveTypeAssignment.ts(3,9): error TS2693: 'number' only refers to a type, but is being used as a value here. +tests/cases/compiler/primitiveTypeAssignment.ts(5,9): error TS2693: 'boolean' only refers to a type, but is being used as a value here. ==== tests/cases/compiler/primitiveTypeAssignment.ts (3 errors) ==== var x = any; ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. var y = number; ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. var z = boolean; ~~~~~~~ -!!! error TS2304: Cannot find name 'boolean'. +!!! error TS2693: 'boolean' only refers to a type, but is being used as a value here. \ No newline at end of file diff --git a/tests/baselines/reference/printerApi/printsNodeCorrectly.classWithOptionalMethodAndProperty.js b/tests/baselines/reference/printerApi/printsNodeCorrectly.classWithOptionalMethodAndProperty.js new file mode 100644 index 00000000000..6626f2e35c9 --- /dev/null +++ b/tests/baselines/reference/printerApi/printsNodeCorrectly.classWithOptionalMethodAndProperty.js @@ -0,0 +1,4 @@ +declare class X { + method?(): void; + property?: string; +} \ No newline at end of file diff --git a/tests/baselines/reference/printerApi/printsNodeCorrectly.namespaceExportDeclaration.js b/tests/baselines/reference/printerApi/printsNodeCorrectly.namespaceExportDeclaration.js new file mode 100644 index 00000000000..725da0cef9f --- /dev/null +++ b/tests/baselines/reference/printerApi/printsNodeCorrectly.namespaceExportDeclaration.js @@ -0,0 +1 @@ +export as namespace B; \ No newline at end of file diff --git a/tests/baselines/reference/privateIndexer2.errors.txt b/tests/baselines/reference/privateIndexer2.errors.txt index 9f087b22379..7e826dbc7a9 100644 --- a/tests/baselines/reference/privateIndexer2.errors.txt +++ b/tests/baselines/reference/privateIndexer2.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,15): error TS1005: ']' expected. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,17): error TS2304: Cannot find name 'string'. +tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,17): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,23): error TS1005: ',' expected. tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,24): error TS1136: Property assignment expected. tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,32): error TS1005: ':' expected. @@ -13,7 +13,7 @@ tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,32) ~ !!! error TS1005: ']' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ',' expected. ~ diff --git a/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/amd/visibilityOfTypeUsedAcrossModules2.errors.txt b/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/amd/visibilityOfTypeUsedAcrossModules2.errors.txt index d5c992fff66..88f77a6a2e8 100644 --- a/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/amd/visibilityOfTypeUsedAcrossModules2.errors.txt +++ b/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/amd/visibilityOfTypeUsedAcrossModules2.errors.txt @@ -1,15 +1,15 @@ -main.ts(1,1): error TS1006: A file cannot have a reference to itself. -main.ts(2,1): error TS6053: File 'nonExistingFile1.ts' not found. -main.ts(3,1): error TS6053: File 'nonExistingFile2.ts' not found. +main.ts(1,22): error TS1006: A file cannot have a reference to itself. +main.ts(2,22): error TS6053: File 'nonExistingFile1.ts' not found. +main.ts(3,22): error TS6053: File 'nonExistingFile2.ts' not found. ==== main.ts (3 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~ !!! error TS1006: A file cannot have a reference to itself. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'nonExistingFile1.ts' not found. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'nonExistingFile2.ts' not found. \ No newline at end of file diff --git a/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/node/visibilityOfTypeUsedAcrossModules2.errors.txt b/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/node/visibilityOfTypeUsedAcrossModules2.errors.txt index d5c992fff66..88f77a6a2e8 100644 --- a/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/node/visibilityOfTypeUsedAcrossModules2.errors.txt +++ b/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/node/visibilityOfTypeUsedAcrossModules2.errors.txt @@ -1,15 +1,15 @@ -main.ts(1,1): error TS1006: A file cannot have a reference to itself. -main.ts(2,1): error TS6053: File 'nonExistingFile1.ts' not found. -main.ts(3,1): error TS6053: File 'nonExistingFile2.ts' not found. +main.ts(1,22): error TS1006: A file cannot have a reference to itself. +main.ts(2,22): error TS6053: File 'nonExistingFile1.ts' not found. +main.ts(3,22): error TS6053: File 'nonExistingFile2.ts' not found. ==== main.ts (3 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~ !!! error TS1006: A file cannot have a reference to itself. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'nonExistingFile1.ts' not found. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'nonExistingFile2.ts' not found. \ No newline at end of file diff --git a/tests/baselines/reference/propertyOrdering.errors.txt b/tests/baselines/reference/propertyOrdering.errors.txt index ded6ec01aff..f9f638f592d 100644 --- a/tests/baselines/reference/propertyOrdering.errors.txt +++ b/tests/baselines/reference/propertyOrdering.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/propertyOrdering.ts(6,23): error TS2304: Cannot find name 'store'. -tests/cases/compiler/propertyOrdering.ts(9,34): error TS2339: Property 'store' does not exist on type 'Foo'. +tests/cases/compiler/propertyOrdering.ts(9,34): error TS2551: Property 'store' does not exist on type 'Foo'. Did you mean '_store'? tests/cases/compiler/propertyOrdering.ts(16,25): error TS2339: Property '_store' does not exist on type 'Bar'. tests/cases/compiler/propertyOrdering.ts(20,14): error TS2339: Property '_store' does not exist on type 'Bar'. @@ -17,7 +17,7 @@ tests/cases/compiler/propertyOrdering.ts(20,14): error TS2339: Property '_store' public bar() { return this.store; } // should be an error ~~~~~ -!!! error TS2339: Property 'store' does not exist on type 'Foo'. +!!! error TS2551: Property 'store' does not exist on type 'Foo'. Did you mean '_store'? } diff --git a/tests/baselines/reference/propertySignatures.errors.txt b/tests/baselines/reference/propertySignatures.errors.txt index fd415334e74..60a393aef4d 100644 --- a/tests/baselines/reference/propertySignatures.errors.txt +++ b/tests/baselines/reference/propertySignatures.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/propertySignatures.ts(2,13): error TS2300: Duplicate identifier 'a'. tests/cases/compiler/propertySignatures.ts(2,23): error TS2300: Duplicate identifier 'a'. -tests/cases/compiler/propertySignatures.ts(14,12): error TS2304: Cannot find name 'foo'. +tests/cases/compiler/propertySignatures.ts(14,12): error TS2552: Cannot find name 'foo'. Did you mean 'foo1'? ==== tests/cases/compiler/propertySignatures.ts (3 errors) ==== @@ -23,7 +23,7 @@ tests/cases/compiler/propertySignatures.ts(14,12): error TS2304: Cannot find nam var foo4: { (): void; }; var test = foo(); ~~~ -!!! error TS2304: Cannot find name 'foo'. +!!! error TS2552: Cannot find name 'foo'. Did you mean 'foo1'? // Should be OK var foo5: {();}; diff --git a/tests/baselines/reference/recursiveFunctionTypes.errors.txt b/tests/baselines/reference/recursiveFunctionTypes.errors.txt index 8a454133a82..77010d7efa1 100644 --- a/tests/baselines/reference/recursiveFunctionTypes.errors.txt +++ b/tests/baselines/reference/recursiveFunctionTypes.errors.txt @@ -8,9 +8,9 @@ tests/cases/compiler/recursiveFunctionTypes.ts(17,5): error TS2322: Type '() => tests/cases/compiler/recursiveFunctionTypes.ts(22,5): error TS2345: Argument of type '3' is not assignable to parameter of type '(t: typeof g) => void'. tests/cases/compiler/recursiveFunctionTypes.ts(25,1): error TS2322: Type '3' is not assignable to type '() => any'. tests/cases/compiler/recursiveFunctionTypes.ts(30,10): error TS2394: Overload signature is not compatible with function implementation. -tests/cases/compiler/recursiveFunctionTypes.ts(33,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/recursiveFunctionTypes.ts(33,1): error TS2554: Expected 0-1 arguments, but got 2. tests/cases/compiler/recursiveFunctionTypes.ts(34,4): error TS2345: Argument of type '""' is not assignable to parameter of type '{ (): typeof f6; (a: typeof f6): () => number; }'. -tests/cases/compiler/recursiveFunctionTypes.ts(42,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/recursiveFunctionTypes.ts(42,1): error TS2554: Expected 0-1 arguments, but got 2. tests/cases/compiler/recursiveFunctionTypes.ts(43,4): error TS2345: Argument of type '""' is not assignable to parameter of type '{ (): typeof f7; (a: typeof f7): () => number; (a: number): number; (a?: typeof f7): typeof f7; }'. @@ -68,7 +68,7 @@ tests/cases/compiler/recursiveFunctionTypes.ts(43,4): error TS2345: Argument of f6("", 3); // error (arity mismatch) ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0-1 arguments, but got 2. f6(""); // ok (function takes an any param) ~~ !!! error TS2345: Argument of type '""' is not assignable to parameter of type '{ (): typeof f6; (a: typeof f6): () => number; }'. @@ -81,7 +81,7 @@ tests/cases/compiler/recursiveFunctionTypes.ts(43,4): error TS2345: Argument of f7("", 3); // error (arity mismatch) ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0-1 arguments, but got 2. f7(""); // ok (function takes an any param) ~~ !!! error TS2345: Argument of type '""' is not assignable to parameter of type '{ (): typeof f7; (a: typeof f7): () => number; (a: number): number; (a?: typeof f7): typeof f7; }'. diff --git a/tests/baselines/reference/requiredInitializedParameter1.errors.txt b/tests/baselines/reference/requiredInitializedParameter1.errors.txt index ef958dbdec9..31c0f70ee8d 100644 --- a/tests/baselines/reference/requiredInitializedParameter1.errors.txt +++ b/tests/baselines/reference/requiredInitializedParameter1.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/requiredInitializedParameter1.ts(11,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/requiredInitializedParameter1.ts(16,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/requiredInitializedParameter1.ts(11,1): error TS2554: Expected 3 arguments, but got 2. +tests/cases/compiler/requiredInitializedParameter1.ts(16,1): error TS2554: Expected 3 arguments, but got 1. ==== tests/cases/compiler/requiredInitializedParameter1.ts (2 errors) ==== @@ -15,14 +15,14 @@ tests/cases/compiler/requiredInitializedParameter1.ts(16,1): error TS2346: Suppl f1(0, 1); ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 3 arguments, but got 2. f2(0, 1); f3(0, 1); f4(0, 1); f1(0); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 3 arguments, but got 1. f2(0); f3(0); f4(0); \ No newline at end of file diff --git a/tests/baselines/reference/restParamsWithNonRestParams.errors.txt b/tests/baselines/reference/restParamsWithNonRestParams.errors.txt index 4fdb98206c7..cccbba2f4b5 100644 --- a/tests/baselines/reference/restParamsWithNonRestParams.errors.txt +++ b/tests/baselines/reference/restParamsWithNonRestParams.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/restParamsWithNonRestParams.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/restParamsWithNonRestParams.ts(4,1): error TS2555: Expected at least 1 arguments, but got 0. ==== tests/cases/compiler/restParamsWithNonRestParams.ts (1 errors) ==== @@ -7,6 +7,6 @@ tests/cases/compiler/restParamsWithNonRestParams.ts(4,1): error TS2346: Supplied function foo2(a:string, ...b:number[]){} foo2(); // should be an error ~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2555: Expected at least 1 arguments, but got 0. function foo3(a?:string, ...b:number[]){} foo3(); // error but shouldn't be \ No newline at end of file diff --git a/tests/baselines/reference/scannerS7.2_A1.5_T2.errors.txt b/tests/baselines/reference/scannerS7.2_A1.5_T2.errors.txt index 94200267e62..97d580c9b4b 100644 --- a/tests/baselines/reference/scannerS7.2_A1.5_T2.errors.txt +++ b/tests/baselines/reference/scannerS7.2_A1.5_T2.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts(14,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts(20,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts(14,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts(20,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? ==== tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts (2 errors) ==== @@ -18,7 +18,7 @@ tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts(20,3): error if (x !== 1) { $ERROR('#1: eval("\\u00A0var x\\u00A0= 1\\u00A0"); x === 1. Actual: ' + (x)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } //CHECK#2 @@ -26,7 +26,7 @@ tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts(20,3): error if (x !== 1) { $ERROR('#2:  var x = 1 ; x === 1. Actual: ' + (x)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } diff --git a/tests/baselines/reference/scannerS7.3_A1.1_T2.errors.txt b/tests/baselines/reference/scannerS7.3_A1.1_T2.errors.txt index 278e1d79621..186427f5de9 100644 --- a/tests/baselines/reference/scannerS7.3_A1.1_T2.errors.txt +++ b/tests/baselines/reference/scannerS7.3_A1.1_T2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/scanner/ecmascript5/scannerS7.3_A1.1_T2.ts(17,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.3_A1.1_T2.ts(17,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? ==== tests/cases/conformance/scanner/ecmascript5/scannerS7.3_A1.1_T2.ts (1 errors) ==== @@ -20,7 +20,7 @@ tests/cases/conformance/scanner/ecmascript5/scannerS7.3_A1.1_T2.ts(17,3): error if (x !== 1) { $ERROR('#1: var\\nx\\n=\\n1\\n; x === 1. Actual: ' + (x)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } \ No newline at end of file diff --git a/tests/baselines/reference/scannerS7.6_A4.2_T1.errors.txt b/tests/baselines/reference/scannerS7.6_A4.2_T1.errors.txt index 97925d67549..0213122e54f 100644 --- a/tests/baselines/reference/scannerS7.6_A4.2_T1.errors.txt +++ b/tests/baselines/reference/scannerS7.6_A4.2_T1.errors.txt @@ -1,13 +1,13 @@ -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(14,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(18,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(22,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(26,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(30,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(34,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(38,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(42,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(46,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(50,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(14,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(18,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(22,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(26,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(30,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(34,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(38,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(42,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(46,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(50,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(54,3): error TS2304: Cannot find name '$ERROR'. tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(58,3): error TS2304: Cannot find name '$ERROR'. tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(62,3): error TS2304: Cannot find name '$ERROR'. @@ -49,61 +49,61 @@ tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(142,3): error if (А !== 1) { $ERROR('#А'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0411 = 1; if (Б !== 1) { $ERROR('#Б'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0412 = 1; if (В !== 1) { $ERROR('#В'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0413 = 1; if (Г !== 1) { $ERROR('#Г'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0414 = 1; if (Д !== 1) { $ERROR('#Д'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0415 = 1; if (Е !== 1) { $ERROR('#Е'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0416 = 1; if (Ж !== 1) { $ERROR('#Ж'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0417 = 1; if (З !== 1) { $ERROR('#З'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0418 = 1; if (И !== 1) { $ERROR('#И'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0419 = 1; if (Й !== 1) { $ERROR('#Й'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041A = 1; if (К !== 1) { diff --git a/tests/baselines/reference/scannertest1.errors.txt b/tests/baselines/reference/scannertest1.errors.txt index fce2a0b292a..e4059e3881a 100644 --- a/tests/baselines/reference/scannertest1.errors.txt +++ b/tests/baselines/reference/scannertest1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(1,1): error TS6053: File 'tests/cases/conformance/scanner/ecmascript5/References.ts' not found. +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(1,21): error TS6053: File 'tests/cases/conformance/scanner/ecmascript5/References.ts' not found. tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(5,21): error TS2304: Cannot find name 'CharacterCodes'. tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(5,47): error TS2304: Cannot find name 'CharacterCodes'. tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(9,16): error TS2662: Cannot find name 'isDecimalDigit'. Did you mean the static member 'CharacterInfo.isDecimalDigit'? @@ -18,7 +18,7 @@ tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(20,23): error TS2304 ==== tests/cases/conformance/scanner/ecmascript5/scannertest1.ts (16 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/scanner/ecmascript5/References.ts' not found. class CharacterInfo { diff --git a/tests/baselines/reference/selfReferencingFile.errors.txt b/tests/baselines/reference/selfReferencingFile.errors.txt index 8bf68fde774..eddaff4c28d 100644 --- a/tests/baselines/reference/selfReferencingFile.errors.txt +++ b/tests/baselines/reference/selfReferencingFile.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/selfReferencingFile.ts(1,1): error TS1006: A file cannot have a reference to itself. +tests/cases/compiler/selfReferencingFile.ts(1,21): error TS1006: A file cannot have a reference to itself. ==== tests/cases/compiler/selfReferencingFile.ts (1 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~ !!! error TS1006: A file cannot have a reference to itself. class selfReferencingFile { diff --git a/tests/baselines/reference/selfReferencingFile2.errors.txt b/tests/baselines/reference/selfReferencingFile2.errors.txt index 002e087d60e..109a5554ffe 100644 --- a/tests/baselines/reference/selfReferencingFile2.errors.txt +++ b/tests/baselines/reference/selfReferencingFile2.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/selfReferencingFile2.ts(1,1): error TS6053: File 'tests/cases/selfReferencingFile2.ts' not found. +tests/cases/compiler/selfReferencingFile2.ts(1,21): error TS6053: File 'tests/cases/selfReferencingFile2.ts' not found. ==== tests/cases/compiler/selfReferencingFile2.ts (1 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/selfReferencingFile2.ts' not found. class selfReferencingFile2 { diff --git a/tests/baselines/reference/selfReferencingFile3.errors.txt b/tests/baselines/reference/selfReferencingFile3.errors.txt index 05cf04ddc4b..b828ba02d7d 100644 --- a/tests/baselines/reference/selfReferencingFile3.errors.txt +++ b/tests/baselines/reference/selfReferencingFile3.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/selfReferencingFile3.ts(1,1): error TS1006: A file cannot have a reference to itself. +tests/cases/compiler/selfReferencingFile3.ts(1,21): error TS1006: A file cannot have a reference to itself. ==== tests/cases/compiler/selfReferencingFile3.ts (1 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS1006: A file cannot have a reference to itself. class selfReferencingFile3 { diff --git a/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPattern.types b/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPattern.types index eef87d57c45..bbd13dddf57 100644 --- a/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPattern.types +++ b/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPattern.types @@ -37,7 +37,7 @@ var robotA: Robot = { name: "mower", skills: { primary: "mowing", secondary: "no >"none" : "none" function foo1({ skills: { primary: primaryA, secondary: secondaryA } }: Robot) { ->foo1 : ({skills: {primary: primaryA, secondary: secondaryA}}: Robot) => void +>foo1 : ({ skills: { primary: primaryA, secondary: secondaryA } }: Robot) => void >skills : any >primary : any >primaryA : string @@ -53,7 +53,7 @@ function foo1({ skills: { primary: primaryA, secondary: secondaryA } }: Robot) { >primaryA : string } function foo2({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }: Robot) { ->foo2 : ({name: nameC, skills: {primary: primaryB, secondary: secondaryB}}: Robot) => void +>foo2 : ({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }: Robot) => void >name : any >nameC : string >skills : any @@ -71,7 +71,7 @@ function foo2({ name: nameC, skills: { primary: primaryB, secondary: secondaryB >secondaryB : string } function foo3({ skills }: Robot) { ->foo3 : ({skills}: Robot) => void +>foo3 : ({ skills }: Robot) => void >skills : { primary: string; secondary: string; } >Robot : Robot @@ -87,12 +87,12 @@ function foo3({ skills }: Robot) { foo1(robotA); >foo1(robotA) : void ->foo1 : ({skills: {primary: primaryA, secondary: secondaryA}}: Robot) => void +>foo1 : ({ skills: { primary: primaryA, secondary: secondaryA } }: Robot) => void >robotA : Robot foo1({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }); >foo1({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }) : void ->foo1 : ({skills: {primary: primaryA, secondary: secondaryA}}: Robot) => void +>foo1 : ({ skills: { primary: primaryA, secondary: secondaryA } }: Robot) => void >{ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } } : { name: string; skills: { primary: string; secondary: string; }; } >name : string >"Edger" : "Edger" @@ -105,12 +105,12 @@ foo1({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" foo2(robotA); >foo2(robotA) : void ->foo2 : ({name: nameC, skills: {primary: primaryB, secondary: secondaryB}}: Robot) => void +>foo2 : ({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }: Robot) => void >robotA : Robot foo2({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }); >foo2({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }) : void ->foo2 : ({name: nameC, skills: {primary: primaryB, secondary: secondaryB}}: Robot) => void +>foo2 : ({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }: Robot) => void >{ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } } : { name: string; skills: { primary: string; secondary: string; }; } >name : string >"Edger" : "Edger" @@ -123,12 +123,12 @@ foo2({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" foo3(robotA); >foo3(robotA) : void ->foo3 : ({skills}: Robot) => void +>foo3 : ({ skills }: Robot) => void >robotA : Robot foo3({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }); >foo3({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }) : void ->foo3 : ({skills}: Robot) => void +>foo3 : ({ skills }: Robot) => void >{ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } } : { name: string; skills: { primary: string; secondary: string; }; } >name : string >"Edger" : "Edger" diff --git a/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPatternDefaultValues.types b/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPatternDefaultValues.types index 9f5b16407ca..d9c8b319752 100644 --- a/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPatternDefaultValues.types +++ b/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPatternDefaultValues.types @@ -37,7 +37,7 @@ var robotA: Robot = { name: "mower", skills: { primary: "mowing", secondary: "no >"none" : "none" function foo1( ->foo1 : ({skills: {primary: primaryA, secondary: secondaryA}}?: Robot) => void +>foo1 : ({ skills: { primary: primaryA, secondary: secondaryA } }?: Robot) => void { skills: { >skills : any @@ -71,7 +71,7 @@ function foo1( >primaryA : string } function foo2( ->foo2 : ({name: nameC, skills: {primary: primaryB, secondary: secondaryB}}?: Robot) => void +>foo2 : ({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }?: Robot) => void { name: nameC = "name", >name : any @@ -110,7 +110,7 @@ function foo2( >secondaryB : string } function foo3({ skills = { primary: "SomeSkill", secondary: "someSkill" } }: Robot = robotA) { ->foo3 : ({skills}?: Robot) => void +>foo3 : ({ skills }?: Robot) => void >skills : { primary?: string; secondary?: string; } >{ primary: "SomeSkill", secondary: "someSkill" } : { primary: string; secondary: string; } >primary : string @@ -132,12 +132,12 @@ function foo3({ skills = { primary: "SomeSkill", secondary: "someSkill" } }: Ro foo1(robotA); >foo1(robotA) : void ->foo1 : ({skills: {primary: primaryA, secondary: secondaryA}}?: Robot) => void +>foo1 : ({ skills: { primary: primaryA, secondary: secondaryA } }?: Robot) => void >robotA : Robot foo1({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }); >foo1({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }) : void ->foo1 : ({skills: {primary: primaryA, secondary: secondaryA}}?: Robot) => void +>foo1 : ({ skills: { primary: primaryA, secondary: secondaryA } }?: Robot) => void >{ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } } : { name: string; skills: { primary: string; secondary: string; }; } >name : string >"Edger" : "Edger" @@ -150,12 +150,12 @@ foo1({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" foo2(robotA); >foo2(robotA) : void ->foo2 : ({name: nameC, skills: {primary: primaryB, secondary: secondaryB}}?: Robot) => void +>foo2 : ({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }?: Robot) => void >robotA : Robot foo2({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }); >foo2({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }) : void ->foo2 : ({name: nameC, skills: {primary: primaryB, secondary: secondaryB}}?: Robot) => void +>foo2 : ({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }?: Robot) => void >{ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } } : { name: string; skills: { primary: string; secondary: string; }; } >name : string >"Edger" : "Edger" @@ -168,12 +168,12 @@ foo2({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" foo3(robotA); >foo3(robotA) : void ->foo3 : ({skills}?: Robot) => void +>foo3 : ({ skills }?: Robot) => void >robotA : Robot foo3({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }); >foo3({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }) : void ->foo3 : ({skills}?: Robot) => void +>foo3 : ({ skills }?: Robot) => void >{ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } } : { name: string; skills: { primary: string; secondary: string; }; } >name : string >"Edger" : "Edger" diff --git a/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPattern.types b/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPattern.types index 225071a3d2e..5185ab35994 100644 --- a/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPattern.types +++ b/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPattern.types @@ -29,7 +29,7 @@ var robotA: Robot = { name: "mower", skill: "mowing" }; >"mowing" : "mowing" function foo1({ name: nameA }: Robot) { ->foo1 : ({name: nameA}: Robot) => void +>foo1 : ({ name: nameA }: Robot) => void >name : any >nameA : string >Robot : Robot @@ -42,7 +42,7 @@ function foo1({ name: nameA }: Robot) { >nameA : string } function foo2({ name: nameB, skill: skillB }: Robot) { ->foo2 : ({name: nameB, skill: skillB}: Robot) => void +>foo2 : ({ name: nameB, skill: skillB }: Robot) => void >name : any >nameB : string >skill : any @@ -57,7 +57,7 @@ function foo2({ name: nameB, skill: skillB }: Robot) { >nameB : string } function foo3({ name }: Robot) { ->foo3 : ({name}: Robot) => void +>foo3 : ({ name }: Robot) => void >name : string >Robot : Robot @@ -71,12 +71,12 @@ function foo3({ name }: Robot) { foo1(robotA); >foo1(robotA) : void ->foo1 : ({name: nameA}: Robot) => void +>foo1 : ({ name: nameA }: Robot) => void >robotA : Robot foo1({ name: "Edger", skill: "cutting edges" }); >foo1({ name: "Edger", skill: "cutting edges" }) : void ->foo1 : ({name: nameA}: Robot) => void +>foo1 : ({ name: nameA }: Robot) => void >{ name: "Edger", skill: "cutting edges" } : { name: string; skill: string; } >name : string >"Edger" : "Edger" @@ -85,12 +85,12 @@ foo1({ name: "Edger", skill: "cutting edges" }); foo2(robotA); >foo2(robotA) : void ->foo2 : ({name: nameB, skill: skillB}: Robot) => void +>foo2 : ({ name: nameB, skill: skillB }: Robot) => void >robotA : Robot foo2({ name: "Edger", skill: "cutting edges" }); >foo2({ name: "Edger", skill: "cutting edges" }) : void ->foo2 : ({name: nameB, skill: skillB}: Robot) => void +>foo2 : ({ name: nameB, skill: skillB }: Robot) => void >{ name: "Edger", skill: "cutting edges" } : { name: string; skill: string; } >name : string >"Edger" : "Edger" @@ -99,12 +99,12 @@ foo2({ name: "Edger", skill: "cutting edges" }); foo3(robotA); >foo3(robotA) : void ->foo3 : ({name}: Robot) => void +>foo3 : ({ name }: Robot) => void >robotA : Robot foo3({ name: "Edger", skill: "cutting edges" }); >foo3({ name: "Edger", skill: "cutting edges" }) : void ->foo3 : ({name}: Robot) => void +>foo3 : ({ name }: Robot) => void >{ name: "Edger", skill: "cutting edges" } : { name: string; skill: string; } >name : string >"Edger" : "Edger" diff --git a/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPatternDefaultValues.types b/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPatternDefaultValues.types index db6a8bcab29..ca6670e5561 100644 --- a/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPatternDefaultValues.types +++ b/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPatternDefaultValues.types @@ -29,7 +29,7 @@ var robotA: Robot = { name: "mower", skill: "mowing" }; >"mowing" : "mowing" function foo1({ name: nameA = "" }: Robot = { }) { ->foo1 : ({name: nameA}?: Robot) => void +>foo1 : ({ name: nameA }?: Robot) => void >name : any >nameA : string >"" : "" @@ -44,7 +44,7 @@ function foo1({ name: nameA = "" }: Robot = { }) { >nameA : string } function foo2({ name: nameB = "", skill: skillB = "noSkill" }: Robot = {}) { ->foo2 : ({name: nameB, skill: skillB}?: Robot) => void +>foo2 : ({ name: nameB, skill: skillB }?: Robot) => void >name : any >nameB : string >"" : "" @@ -62,7 +62,7 @@ function foo2({ name: nameB = "", skill: skillB = "noSkill" }: Robot = { >nameB : string } function foo3({ name = "" }: Robot = {}) { ->foo3 : ({name}?: Robot) => void +>foo3 : ({ name }?: Robot) => void >name : string >"" : "" >Robot : Robot @@ -78,12 +78,12 @@ function foo3({ name = "" }: Robot = {}) { foo1(robotA); >foo1(robotA) : void ->foo1 : ({name: nameA}?: Robot) => void +>foo1 : ({ name: nameA }?: Robot) => void >robotA : Robot foo1({ name: "Edger", skill: "cutting edges" }); >foo1({ name: "Edger", skill: "cutting edges" }) : void ->foo1 : ({name: nameA}?: Robot) => void +>foo1 : ({ name: nameA }?: Robot) => void >{ name: "Edger", skill: "cutting edges" } : { name: string; skill: string; } >name : string >"Edger" : "Edger" @@ -92,12 +92,12 @@ foo1({ name: "Edger", skill: "cutting edges" }); foo2(robotA); >foo2(robotA) : void ->foo2 : ({name: nameB, skill: skillB}?: Robot) => void +>foo2 : ({ name: nameB, skill: skillB }?: Robot) => void >robotA : Robot foo2({ name: "Edger", skill: "cutting edges" }); >foo2({ name: "Edger", skill: "cutting edges" }) : void ->foo2 : ({name: nameB, skill: skillB}?: Robot) => void +>foo2 : ({ name: nameB, skill: skillB }?: Robot) => void >{ name: "Edger", skill: "cutting edges" } : { name: string; skill: string; } >name : string >"Edger" : "Edger" @@ -106,12 +106,12 @@ foo2({ name: "Edger", skill: "cutting edges" }); foo3(robotA); >foo3(robotA) : void ->foo3 : ({name}?: Robot) => void +>foo3 : ({ name }?: Robot) => void >robotA : Robot foo3({ name: "Edger", skill: "cutting edges" }); >foo3({ name: "Edger", skill: "cutting edges" }) : void ->foo3 : ({name}?: Robot) => void +>foo3 : ({ name }?: Robot) => void >{ name: "Edger", skill: "cutting edges" } : { name: string; skill: string; } >name : string >"Edger" : "Edger" diff --git a/tests/baselines/reference/staticsInAFunction.errors.txt b/tests/baselines/reference/staticsInAFunction.errors.txt index 48104fd52f4..254f321913b 100644 --- a/tests/baselines/reference/staticsInAFunction.errors.txt +++ b/tests/baselines/reference/staticsInAFunction.errors.txt @@ -5,12 +5,12 @@ tests/cases/compiler/staticsInAFunction.ts(3,4): error TS1128: Declaration or st tests/cases/compiler/staticsInAFunction.ts(3,11): error TS2304: Cannot find name 'test'. tests/cases/compiler/staticsInAFunction.ts(3,16): error TS2304: Cannot find name 'name'. tests/cases/compiler/staticsInAFunction.ts(3,20): error TS1005: ',' expected. -tests/cases/compiler/staticsInAFunction.ts(3,21): error TS2304: Cannot find name 'string'. +tests/cases/compiler/staticsInAFunction.ts(3,21): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/staticsInAFunction.ts(4,4): error TS1128: Declaration or statement expected. tests/cases/compiler/staticsInAFunction.ts(4,11): error TS2304: Cannot find name 'test'. tests/cases/compiler/staticsInAFunction.ts(4,16): error TS2304: Cannot find name 'name'. tests/cases/compiler/staticsInAFunction.ts(4,21): error TS1109: Expression expected. -tests/cases/compiler/staticsInAFunction.ts(4,22): error TS2304: Cannot find name 'any'. +tests/cases/compiler/staticsInAFunction.ts(4,22): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/staticsInAFunction.ts(4,26): error TS1005: ';' expected. @@ -33,7 +33,7 @@ tests/cases/compiler/staticsInAFunction.ts(4,26): error TS1005: ';' expected. ~ !!! error TS1005: ',' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. static test(name?:any){} ~~~~~~ !!! error TS1128: Declaration or statement expected. @@ -44,7 +44,7 @@ tests/cases/compiler/staticsInAFunction.ts(4,26): error TS1005: ';' expected. ~ !!! error TS1109: Expression expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. } diff --git a/tests/baselines/reference/strictModeReservedWord.errors.txt b/tests/baselines/reference/strictModeReservedWord.errors.txt index 5a6de7792b7..f2f74c81a93 100644 --- a/tests/baselines/reference/strictModeReservedWord.errors.txt +++ b/tests/baselines/reference/strictModeReservedWord.errors.txt @@ -38,7 +38,7 @@ tests/cases/compiler/strictModeReservedWord.ts(22,12): error TS1212: Identifier tests/cases/compiler/strictModeReservedWord.ts(22,12): error TS2503: Cannot find namespace 'interface'. tests/cases/compiler/strictModeReservedWord.ts(22,22): error TS1212: Identifier expected. 'package' is a reserved word in strict mode. tests/cases/compiler/strictModeReservedWord.ts(22,30): error TS1212: Identifier expected. 'implements' is a reserved word in strict mode. -tests/cases/compiler/strictModeReservedWord.ts(23,5): error TS2304: Cannot find name 'ublic'. +tests/cases/compiler/strictModeReservedWord.ts(23,5): error TS2552: Cannot find name 'ublic'. Did you mean 'public'? tests/cases/compiler/strictModeReservedWord.ts(24,5): error TS1212: Identifier expected. 'static' is a reserved word in strict mode. tests/cases/compiler/strictModeReservedWord.ts(24,5): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. @@ -148,7 +148,7 @@ tests/cases/compiler/strictModeReservedWord.ts(24,5): error TS2349: Cannot invok !!! error TS1212: Identifier expected. 'implements' is a reserved word in strict mode. ublic(); ~~~~~ -!!! error TS2304: Cannot find name 'ublic'. +!!! error TS2552: Cannot find name 'ublic'. Did you mean 'public'? static(); ~~~~~~ !!! error TS1212: Identifier expected. 'static' is a reserved word in strict mode. diff --git a/tests/baselines/reference/stringEnumLiteralTypes1.js b/tests/baselines/reference/stringEnumLiteralTypes1.js new file mode 100644 index 00000000000..4acf2ada1a8 --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes1.js @@ -0,0 +1,178 @@ +//// [stringEnumLiteralTypes1.ts] +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + +type YesNo = Choice.Yes | Choice.No; +type NoYes = Choice.No | Choice.Yes; +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + +function f1() { + var a: YesNo; + var a: NoYes; + var a: Choice.Yes | Choice.No; + var a: Choice.No | Choice.Yes; +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { + b = a; + c = a; + c = b; +} + +function f3(a: Choice.Yes, b: YesNo) { + var x = a + b; + var y = a == b; + var y = a != b; + var y = a === b; + var y = a !== b; + var y = a > b; + var y = a < b; + var y = a >= b; + var y = a <= b; + var y = !b; +} + +declare function g(x: Choice.Yes): string; +declare function g(x: Choice.No): boolean; +declare function g(x: Choice): number; + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { + var z1 = g(Choice.Yes); + var z2 = g(Choice.No); + var z3 = g(a); + var z4 = g(b); + var z5 = g(c); +} + +function assertNever(x: never): never { + throw new Error("Unexpected value"); +} + +function f10(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } +} + +function f11(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } + return assertNever(x); +} + +function f12(x: UnknownYesNo) { + if (x) { + x; + } + else { + x; + } +} + +function f13(x: UnknownYesNo) { + if (x === Choice.Yes) { + x; + } + else { + x; + } +} + +type Item = + { kind: Choice.Yes, a: string } | + { kind: Choice.No, b: string }; + +function f20(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } +} + +function f21(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } + return assertNever(x); +} + +//// [stringEnumLiteralTypes1.js] +; +function f1() { + var a; + var a; + var a; + var a; +} +function f2(a, b, c) { + b = a; + c = a; + c = b; +} +function f3(a, b) { + var x = a + b; + var y = a == b; + var y = a != b; + var y = a === b; + var y = a !== b; + var y = a > b; + var y = a < b; + var y = a >= b; + var y = a <= b; + var y = !b; +} +function f5(a, b, c) { + var z1 = g("yes" /* Yes */); + var z2 = g("no" /* No */); + var z3 = g(a); + var z4 = g(b); + var z5 = g(c); +} +function assertNever(x) { + throw new Error("Unexpected value"); +} +function f10(x) { + switch (x) { + case "yes" /* Yes */: return "true"; + case "no" /* No */: return "false"; + } +} +function f11(x) { + switch (x) { + case "yes" /* Yes */: return "true"; + case "no" /* No */: return "false"; + } + return assertNever(x); +} +function f12(x) { + if (x) { + x; + } + else { + x; + } +} +function f13(x) { + if (x === "yes" /* Yes */) { + x; + } + else { + x; + } +} +function f20(x) { + switch (x.kind) { + case "yes" /* Yes */: return x.a; + case "no" /* No */: return x.b; + } +} +function f21(x) { + switch (x.kind) { + case "yes" /* Yes */: return x.a; + case "no" /* No */: return x.b; + } + return assertNever(x); +} diff --git a/tests/baselines/reference/stringEnumLiteralTypes1.symbols b/tests/baselines/reference/stringEnumLiteralTypes1.symbols new file mode 100644 index 00000000000..66c25aab85c --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes1.symbols @@ -0,0 +1,353 @@ +=== tests/cases/conformance/types/literal/stringEnumLiteralTypes1.ts === +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Unknown : Symbol(Choice.Unknown, Decl(stringEnumLiteralTypes1.ts, 0, 19)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + +type YesNo = Choice.Yes | Choice.No; +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + +type NoYes = Choice.No | Choice.Yes; +>NoYes : Symbol(NoYes, Decl(stringEnumLiteralTypes1.ts, 2, 36)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) + +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes1.ts, 3, 36)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Unknown : Symbol(Choice.Unknown, Decl(stringEnumLiteralTypes1.ts, 0, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + +function f1() { +>f1 : Symbol(f1, Decl(stringEnumLiteralTypes1.ts, 4, 60)) + + var a: YesNo; +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 7, 7), Decl(stringEnumLiteralTypes1.ts, 8, 7), Decl(stringEnumLiteralTypes1.ts, 9, 7), Decl(stringEnumLiteralTypes1.ts, 10, 7)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) + + var a: NoYes; +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 7, 7), Decl(stringEnumLiteralTypes1.ts, 8, 7), Decl(stringEnumLiteralTypes1.ts, 9, 7), Decl(stringEnumLiteralTypes1.ts, 10, 7)) +>NoYes : Symbol(NoYes, Decl(stringEnumLiteralTypes1.ts, 2, 36)) + + var a: Choice.Yes | Choice.No; +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 7, 7), Decl(stringEnumLiteralTypes1.ts, 8, 7), Decl(stringEnumLiteralTypes1.ts, 9, 7), Decl(stringEnumLiteralTypes1.ts, 10, 7)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + + var a: Choice.No | Choice.Yes; +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 7, 7), Decl(stringEnumLiteralTypes1.ts, 8, 7), Decl(stringEnumLiteralTypes1.ts, 9, 7), Decl(stringEnumLiteralTypes1.ts, 10, 7)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { +>f2 : Symbol(f2, Decl(stringEnumLiteralTypes1.ts, 11, 1)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 13, 12)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 13, 21)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes1.ts, 3, 36)) +>c : Symbol(c, Decl(stringEnumLiteralTypes1.ts, 13, 38)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) + + b = a; +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 13, 21)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 13, 12)) + + c = a; +>c : Symbol(c, Decl(stringEnumLiteralTypes1.ts, 13, 38)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 13, 12)) + + c = b; +>c : Symbol(c, Decl(stringEnumLiteralTypes1.ts, 13, 38)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 13, 21)) +} + +function f3(a: Choice.Yes, b: YesNo) { +>f3 : Symbol(f3, Decl(stringEnumLiteralTypes1.ts, 17, 1)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) + + var x = a + b; +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 20, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a == b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a != b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a === b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a !== b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a > b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a < b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a >= b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a <= b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = !b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) +} + +declare function g(x: Choice.Yes): string; +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 32, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) + +declare function g(x: Choice.No): boolean; +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 33, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + +declare function g(x: Choice): number; +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 34, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { +>f5 : Symbol(f5, Decl(stringEnumLiteralTypes1.ts, 34, 38)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 36, 12)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 36, 21)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes1.ts, 3, 36)) +>c : Symbol(c, Decl(stringEnumLiteralTypes1.ts, 36, 38)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) + + var z1 = g(Choice.Yes); +>z1 : Symbol(z1, Decl(stringEnumLiteralTypes1.ts, 37, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) + + var z2 = g(Choice.No); +>z2 : Symbol(z2, Decl(stringEnumLiteralTypes1.ts, 38, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + + var z3 = g(a); +>z3 : Symbol(z3, Decl(stringEnumLiteralTypes1.ts, 39, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 36, 12)) + + var z4 = g(b); +>z4 : Symbol(z4, Decl(stringEnumLiteralTypes1.ts, 40, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 36, 21)) + + var z5 = g(c); +>z5 : Symbol(z5, Decl(stringEnumLiteralTypes1.ts, 41, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>c : Symbol(c, Decl(stringEnumLiteralTypes1.ts, 36, 38)) +} + +function assertNever(x: never): never { +>assertNever : Symbol(assertNever, Decl(stringEnumLiteralTypes1.ts, 42, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 44, 21)) + + throw new Error("Unexpected value"); +>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +} + +function f10(x: YesNo) { +>f10 : Symbol(f10, Decl(stringEnumLiteralTypes1.ts, 46, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 48, 13)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) + + switch (x) { +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 48, 13)) + + case Choice.Yes: return "true"; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) + + case Choice.No: return "false"; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + } +} + +function f11(x: YesNo) { +>f11 : Symbol(f11, Decl(stringEnumLiteralTypes1.ts, 53, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 55, 13)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) + + switch (x) { +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 55, 13)) + + case Choice.Yes: return "true"; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) + + case Choice.No: return "false"; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + } + return assertNever(x); +>assertNever : Symbol(assertNever, Decl(stringEnumLiteralTypes1.ts, 42, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 55, 13)) +} + +function f12(x: UnknownYesNo) { +>f12 : Symbol(f12, Decl(stringEnumLiteralTypes1.ts, 61, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 63, 13)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes1.ts, 3, 36)) + + if (x) { +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 63, 13)) + + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 63, 13)) + } + else { + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 63, 13)) + } +} + +function f13(x: UnknownYesNo) { +>f13 : Symbol(f13, Decl(stringEnumLiteralTypes1.ts, 70, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 72, 13)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes1.ts, 3, 36)) + + if (x === Choice.Yes) { +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 72, 13)) +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) + + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 72, 13)) + } + else { + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 72, 13)) + } +} + +type Item = +>Item : Symbol(Item, Decl(stringEnumLiteralTypes1.ts, 79, 1)) + + { kind: Choice.Yes, a: string } | +>kind : Symbol(kind, Decl(stringEnumLiteralTypes1.ts, 82, 5)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 82, 23)) + + { kind: Choice.No, b: string }; +>kind : Symbol(kind, Decl(stringEnumLiteralTypes1.ts, 83, 5)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 83, 22)) + +function f20(x: Item) { +>f20 : Symbol(f20, Decl(stringEnumLiteralTypes1.ts, 83, 35)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 85, 13)) +>Item : Symbol(Item, Decl(stringEnumLiteralTypes1.ts, 79, 1)) + + switch (x.kind) { +>x.kind : Symbol(kind, Decl(stringEnumLiteralTypes1.ts, 82, 5), Decl(stringEnumLiteralTypes1.ts, 83, 5)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 85, 13)) +>kind : Symbol(kind, Decl(stringEnumLiteralTypes1.ts, 82, 5), Decl(stringEnumLiteralTypes1.ts, 83, 5)) + + case Choice.Yes: return x.a; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>x.a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 82, 23)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 85, 13)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 82, 23)) + + case Choice.No: return x.b; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>x.b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 83, 22)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 85, 13)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 83, 22)) + } +} + +function f21(x: Item) { +>f21 : Symbol(f21, Decl(stringEnumLiteralTypes1.ts, 90, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 92, 13)) +>Item : Symbol(Item, Decl(stringEnumLiteralTypes1.ts, 79, 1)) + + switch (x.kind) { +>x.kind : Symbol(kind, Decl(stringEnumLiteralTypes1.ts, 82, 5), Decl(stringEnumLiteralTypes1.ts, 83, 5)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 92, 13)) +>kind : Symbol(kind, Decl(stringEnumLiteralTypes1.ts, 82, 5), Decl(stringEnumLiteralTypes1.ts, 83, 5)) + + case Choice.Yes: return x.a; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>x.a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 82, 23)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 92, 13)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 82, 23)) + + case Choice.No: return x.b; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>x.b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 83, 22)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 92, 13)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 83, 22)) + } + return assertNever(x); +>assertNever : Symbol(assertNever, Decl(stringEnumLiteralTypes1.ts, 42, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 92, 13)) +} diff --git a/tests/baselines/reference/stringEnumLiteralTypes1.types b/tests/baselines/reference/stringEnumLiteralTypes1.types new file mode 100644 index 00000000000..b5d70ed501f --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes1.types @@ -0,0 +1,383 @@ +=== tests/cases/conformance/types/literal/stringEnumLiteralTypes1.ts === +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; +>Choice : Choice +>Unknown : Choice.Unknown +>"" : "" +>Yes : Choice.Yes +>"yes" : "yes" +>No : Choice.No +>"no" : "no" + +type YesNo = Choice.Yes | Choice.No; +>YesNo : YesNo +>Choice : any +>Yes : Choice.Yes +>Choice : any +>No : Choice.No + +type NoYes = Choice.No | Choice.Yes; +>NoYes : YesNo +>Choice : any +>No : Choice.No +>Choice : any +>Yes : Choice.Yes + +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; +>UnknownYesNo : Choice +>Choice : any +>Unknown : Choice.Unknown +>Choice : any +>Yes : Choice.Yes +>Choice : any +>No : Choice.No + +function f1() { +>f1 : () => void + + var a: YesNo; +>a : YesNo +>YesNo : YesNo + + var a: NoYes; +>a : YesNo +>NoYes : YesNo + + var a: Choice.Yes | Choice.No; +>a : YesNo +>Choice : any +>Yes : Choice.Yes +>Choice : any +>No : Choice.No + + var a: Choice.No | Choice.Yes; +>a : YesNo +>Choice : any +>No : Choice.No +>Choice : any +>Yes : Choice.Yes +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { +>f2 : (a: YesNo, b: Choice, c: Choice) => void +>a : YesNo +>YesNo : YesNo +>b : Choice +>UnknownYesNo : Choice +>c : Choice +>Choice : Choice + + b = a; +>b = a : YesNo +>b : Choice +>a : YesNo + + c = a; +>c = a : YesNo +>c : Choice +>a : YesNo + + c = b; +>c = b : YesNo +>c : Choice +>b : YesNo +} + +function f3(a: Choice.Yes, b: YesNo) { +>f3 : (a: Choice.Yes, b: YesNo) => void +>a : Choice.Yes +>Choice : any +>Yes : Choice.Yes +>b : YesNo +>YesNo : YesNo + + var x = a + b; +>x : string +>a + b : string +>a : Choice.Yes +>b : YesNo + + var y = a == b; +>y : boolean +>a == b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a != b; +>y : boolean +>a != b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a === b; +>y : boolean +>a === b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a !== b; +>y : boolean +>a !== b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a > b; +>y : boolean +>a > b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a < b; +>y : boolean +>a < b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a >= b; +>y : boolean +>a >= b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a <= b; +>y : boolean +>a <= b : boolean +>a : Choice.Yes +>b : YesNo + + var y = !b; +>y : boolean +>!b : boolean +>b : YesNo +} + +declare function g(x: Choice.Yes): string; +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>x : Choice.Yes +>Choice : any +>Yes : Choice.Yes + +declare function g(x: Choice.No): boolean; +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>x : Choice.No +>Choice : any +>No : Choice.No + +declare function g(x: Choice): number; +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>x : Choice +>Choice : Choice + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { +>f5 : (a: YesNo, b: Choice, c: Choice) => void +>a : YesNo +>YesNo : YesNo +>b : Choice +>UnknownYesNo : Choice +>c : Choice +>Choice : Choice + + var z1 = g(Choice.Yes); +>z1 : string +>g(Choice.Yes) : string +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes + + var z2 = g(Choice.No); +>z2 : boolean +>g(Choice.No) : boolean +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No + + var z3 = g(a); +>z3 : number +>g(a) : number +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>a : YesNo + + var z4 = g(b); +>z4 : number +>g(b) : number +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>b : Choice + + var z5 = g(c); +>z5 : number +>g(c) : number +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>c : Choice +} + +function assertNever(x: never): never { +>assertNever : (x: never) => never +>x : never + + throw new Error("Unexpected value"); +>new Error("Unexpected value") : Error +>Error : ErrorConstructor +>"Unexpected value" : "Unexpected value" +} + +function f10(x: YesNo) { +>f10 : (x: YesNo) => "true" | "false" +>x : YesNo +>YesNo : YesNo + + switch (x) { +>x : YesNo + + case Choice.Yes: return "true"; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>"true" : "true" + + case Choice.No: return "false"; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>"false" : "false" + } +} + +function f11(x: YesNo) { +>f11 : (x: YesNo) => "true" | "false" +>x : YesNo +>YesNo : YesNo + + switch (x) { +>x : YesNo + + case Choice.Yes: return "true"; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>"true" : "true" + + case Choice.No: return "false"; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>"false" : "false" + } + return assertNever(x); +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never +} + +function f12(x: UnknownYesNo) { +>f12 : (x: Choice) => void +>x : Choice +>UnknownYesNo : Choice + + if (x) { +>x : Choice + + x; +>x : YesNo + } + else { + x; +>x : Choice + } +} + +function f13(x: UnknownYesNo) { +>f13 : (x: Choice) => void +>x : Choice +>UnknownYesNo : Choice + + if (x === Choice.Yes) { +>x === Choice.Yes : boolean +>x : Choice +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes + + x; +>x : Choice.Yes + } + else { + x; +>x : Choice.Unknown | Choice.No + } +} + +type Item = +>Item : Item + + { kind: Choice.Yes, a: string } | +>kind : Choice.Yes +>Choice : any +>Yes : Choice.Yes +>a : string + + { kind: Choice.No, b: string }; +>kind : Choice.No +>Choice : any +>No : Choice.No +>b : string + +function f20(x: Item) { +>f20 : (x: Item) => string +>x : Item +>Item : Item + + switch (x.kind) { +>x.kind : YesNo +>x : Item +>kind : YesNo + + case Choice.Yes: return x.a; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>x.a : string +>x : { kind: Choice.Yes; a: string; } +>a : string + + case Choice.No: return x.b; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>x.b : string +>x : { kind: Choice.No; b: string; } +>b : string + } +} + +function f21(x: Item) { +>f21 : (x: Item) => string +>x : Item +>Item : Item + + switch (x.kind) { +>x.kind : YesNo +>x : Item +>kind : YesNo + + case Choice.Yes: return x.a; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>x.a : string +>x : { kind: Choice.Yes; a: string; } +>a : string + + case Choice.No: return x.b; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>x.b : string +>x : { kind: Choice.No; b: string; } +>b : string + } + return assertNever(x); +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never +} diff --git a/tests/baselines/reference/stringEnumLiteralTypes2.js b/tests/baselines/reference/stringEnumLiteralTypes2.js new file mode 100644 index 00000000000..07a5de7a85d --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes2.js @@ -0,0 +1,178 @@ +//// [stringEnumLiteralTypes2.ts] +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + +type YesNo = Choice.Yes | Choice.No; +type NoYes = Choice.No | Choice.Yes; +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + +function f1() { + var a: YesNo; + var a: NoYes; + var a: Choice.Yes | Choice.No; + var a: Choice.No | Choice.Yes; +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { + b = a; + c = a; + c = b; +} + +function f3(a: Choice.Yes, b: YesNo) { + var x = a + b; + var y = a == b; + var y = a != b; + var y = a === b; + var y = a !== b; + var y = a > b; + var y = a < b; + var y = a >= b; + var y = a <= b; + var y = !b; +} + +declare function g(x: Choice.Yes): string; +declare function g(x: Choice.No): boolean; +declare function g(x: Choice): number; + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { + var z1 = g(Choice.Yes); + var z2 = g(Choice.No); + var z3 = g(a); + var z4 = g(b); + var z5 = g(c); +} + +function assertNever(x: never): never { + throw new Error("Unexpected value"); +} + +function f10(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } +} + +function f11(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } + return assertNever(x); +} + +function f12(x: UnknownYesNo) { + if (x) { + x; + } + else { + x; + } +} + +function f13(x: UnknownYesNo) { + if (x === Choice.Yes) { + x; + } + else { + x; + } +} + +type Item = + { kind: Choice.Yes, a: string } | + { kind: Choice.No, b: string }; + +function f20(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } +} + +function f21(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } + return assertNever(x); +} + +//// [stringEnumLiteralTypes2.js] +; +function f1() { + var a; + var a; + var a; + var a; +} +function f2(a, b, c) { + b = a; + c = a; + c = b; +} +function f3(a, b) { + var x = a + b; + var y = a == b; + var y = a != b; + var y = a === b; + var y = a !== b; + var y = a > b; + var y = a < b; + var y = a >= b; + var y = a <= b; + var y = !b; +} +function f5(a, b, c) { + var z1 = g("yes" /* Yes */); + var z2 = g("no" /* No */); + var z3 = g(a); + var z4 = g(b); + var z5 = g(c); +} +function assertNever(x) { + throw new Error("Unexpected value"); +} +function f10(x) { + switch (x) { + case "yes" /* Yes */: return "true"; + case "no" /* No */: return "false"; + } +} +function f11(x) { + switch (x) { + case "yes" /* Yes */: return "true"; + case "no" /* No */: return "false"; + } + return assertNever(x); +} +function f12(x) { + if (x) { + x; + } + else { + x; + } +} +function f13(x) { + if (x === "yes" /* Yes */) { + x; + } + else { + x; + } +} +function f20(x) { + switch (x.kind) { + case "yes" /* Yes */: return x.a; + case "no" /* No */: return x.b; + } +} +function f21(x) { + switch (x.kind) { + case "yes" /* Yes */: return x.a; + case "no" /* No */: return x.b; + } + return assertNever(x); +} diff --git a/tests/baselines/reference/stringEnumLiteralTypes2.symbols b/tests/baselines/reference/stringEnumLiteralTypes2.symbols new file mode 100644 index 00000000000..f746c0430cb --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes2.symbols @@ -0,0 +1,353 @@ +=== tests/cases/conformance/types/literal/stringEnumLiteralTypes2.ts === +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Unknown : Symbol(Choice.Unknown, Decl(stringEnumLiteralTypes2.ts, 0, 19)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + +type YesNo = Choice.Yes | Choice.No; +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + +type NoYes = Choice.No | Choice.Yes; +>NoYes : Symbol(NoYes, Decl(stringEnumLiteralTypes2.ts, 2, 36)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) + +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes2.ts, 3, 36)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Unknown : Symbol(Choice.Unknown, Decl(stringEnumLiteralTypes2.ts, 0, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + +function f1() { +>f1 : Symbol(f1, Decl(stringEnumLiteralTypes2.ts, 4, 60)) + + var a: YesNo; +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 7, 7), Decl(stringEnumLiteralTypes2.ts, 8, 7), Decl(stringEnumLiteralTypes2.ts, 9, 7), Decl(stringEnumLiteralTypes2.ts, 10, 7)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) + + var a: NoYes; +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 7, 7), Decl(stringEnumLiteralTypes2.ts, 8, 7), Decl(stringEnumLiteralTypes2.ts, 9, 7), Decl(stringEnumLiteralTypes2.ts, 10, 7)) +>NoYes : Symbol(NoYes, Decl(stringEnumLiteralTypes2.ts, 2, 36)) + + var a: Choice.Yes | Choice.No; +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 7, 7), Decl(stringEnumLiteralTypes2.ts, 8, 7), Decl(stringEnumLiteralTypes2.ts, 9, 7), Decl(stringEnumLiteralTypes2.ts, 10, 7)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + + var a: Choice.No | Choice.Yes; +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 7, 7), Decl(stringEnumLiteralTypes2.ts, 8, 7), Decl(stringEnumLiteralTypes2.ts, 9, 7), Decl(stringEnumLiteralTypes2.ts, 10, 7)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { +>f2 : Symbol(f2, Decl(stringEnumLiteralTypes2.ts, 11, 1)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 13, 12)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 13, 21)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes2.ts, 3, 36)) +>c : Symbol(c, Decl(stringEnumLiteralTypes2.ts, 13, 38)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) + + b = a; +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 13, 21)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 13, 12)) + + c = a; +>c : Symbol(c, Decl(stringEnumLiteralTypes2.ts, 13, 38)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 13, 12)) + + c = b; +>c : Symbol(c, Decl(stringEnumLiteralTypes2.ts, 13, 38)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 13, 21)) +} + +function f3(a: Choice.Yes, b: YesNo) { +>f3 : Symbol(f3, Decl(stringEnumLiteralTypes2.ts, 17, 1)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) + + var x = a + b; +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 20, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a == b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a != b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a === b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a !== b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a > b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a < b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a >= b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a <= b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = !b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) +} + +declare function g(x: Choice.Yes): string; +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 32, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) + +declare function g(x: Choice.No): boolean; +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 33, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + +declare function g(x: Choice): number; +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 34, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { +>f5 : Symbol(f5, Decl(stringEnumLiteralTypes2.ts, 34, 38)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 36, 12)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 36, 21)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes2.ts, 3, 36)) +>c : Symbol(c, Decl(stringEnumLiteralTypes2.ts, 36, 38)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) + + var z1 = g(Choice.Yes); +>z1 : Symbol(z1, Decl(stringEnumLiteralTypes2.ts, 37, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) + + var z2 = g(Choice.No); +>z2 : Symbol(z2, Decl(stringEnumLiteralTypes2.ts, 38, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + + var z3 = g(a); +>z3 : Symbol(z3, Decl(stringEnumLiteralTypes2.ts, 39, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 36, 12)) + + var z4 = g(b); +>z4 : Symbol(z4, Decl(stringEnumLiteralTypes2.ts, 40, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 36, 21)) + + var z5 = g(c); +>z5 : Symbol(z5, Decl(stringEnumLiteralTypes2.ts, 41, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>c : Symbol(c, Decl(stringEnumLiteralTypes2.ts, 36, 38)) +} + +function assertNever(x: never): never { +>assertNever : Symbol(assertNever, Decl(stringEnumLiteralTypes2.ts, 42, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 44, 21)) + + throw new Error("Unexpected value"); +>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +} + +function f10(x: YesNo) { +>f10 : Symbol(f10, Decl(stringEnumLiteralTypes2.ts, 46, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 48, 13)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) + + switch (x) { +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 48, 13)) + + case Choice.Yes: return "true"; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) + + case Choice.No: return "false"; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + } +} + +function f11(x: YesNo) { +>f11 : Symbol(f11, Decl(stringEnumLiteralTypes2.ts, 53, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 55, 13)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) + + switch (x) { +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 55, 13)) + + case Choice.Yes: return "true"; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) + + case Choice.No: return "false"; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + } + return assertNever(x); +>assertNever : Symbol(assertNever, Decl(stringEnumLiteralTypes2.ts, 42, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 55, 13)) +} + +function f12(x: UnknownYesNo) { +>f12 : Symbol(f12, Decl(stringEnumLiteralTypes2.ts, 61, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 63, 13)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes2.ts, 3, 36)) + + if (x) { +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 63, 13)) + + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 63, 13)) + } + else { + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 63, 13)) + } +} + +function f13(x: UnknownYesNo) { +>f13 : Symbol(f13, Decl(stringEnumLiteralTypes2.ts, 70, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 72, 13)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes2.ts, 3, 36)) + + if (x === Choice.Yes) { +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 72, 13)) +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) + + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 72, 13)) + } + else { + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 72, 13)) + } +} + +type Item = +>Item : Symbol(Item, Decl(stringEnumLiteralTypes2.ts, 79, 1)) + + { kind: Choice.Yes, a: string } | +>kind : Symbol(kind, Decl(stringEnumLiteralTypes2.ts, 82, 5)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 82, 23)) + + { kind: Choice.No, b: string }; +>kind : Symbol(kind, Decl(stringEnumLiteralTypes2.ts, 83, 5)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 83, 22)) + +function f20(x: Item) { +>f20 : Symbol(f20, Decl(stringEnumLiteralTypes2.ts, 83, 35)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 85, 13)) +>Item : Symbol(Item, Decl(stringEnumLiteralTypes2.ts, 79, 1)) + + switch (x.kind) { +>x.kind : Symbol(kind, Decl(stringEnumLiteralTypes2.ts, 82, 5), Decl(stringEnumLiteralTypes2.ts, 83, 5)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 85, 13)) +>kind : Symbol(kind, Decl(stringEnumLiteralTypes2.ts, 82, 5), Decl(stringEnumLiteralTypes2.ts, 83, 5)) + + case Choice.Yes: return x.a; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>x.a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 82, 23)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 85, 13)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 82, 23)) + + case Choice.No: return x.b; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>x.b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 83, 22)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 85, 13)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 83, 22)) + } +} + +function f21(x: Item) { +>f21 : Symbol(f21, Decl(stringEnumLiteralTypes2.ts, 90, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 92, 13)) +>Item : Symbol(Item, Decl(stringEnumLiteralTypes2.ts, 79, 1)) + + switch (x.kind) { +>x.kind : Symbol(kind, Decl(stringEnumLiteralTypes2.ts, 82, 5), Decl(stringEnumLiteralTypes2.ts, 83, 5)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 92, 13)) +>kind : Symbol(kind, Decl(stringEnumLiteralTypes2.ts, 82, 5), Decl(stringEnumLiteralTypes2.ts, 83, 5)) + + case Choice.Yes: return x.a; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>x.a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 82, 23)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 92, 13)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 82, 23)) + + case Choice.No: return x.b; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>x.b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 83, 22)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 92, 13)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 83, 22)) + } + return assertNever(x); +>assertNever : Symbol(assertNever, Decl(stringEnumLiteralTypes2.ts, 42, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 92, 13)) +} diff --git a/tests/baselines/reference/stringEnumLiteralTypes2.types b/tests/baselines/reference/stringEnumLiteralTypes2.types new file mode 100644 index 00000000000..7e4a51d9aea --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes2.types @@ -0,0 +1,383 @@ +=== tests/cases/conformance/types/literal/stringEnumLiteralTypes2.ts === +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; +>Choice : Choice +>Unknown : Choice.Unknown +>"" : "" +>Yes : Choice.Yes +>"yes" : "yes" +>No : Choice.No +>"no" : "no" + +type YesNo = Choice.Yes | Choice.No; +>YesNo : YesNo +>Choice : any +>Yes : Choice.Yes +>Choice : any +>No : Choice.No + +type NoYes = Choice.No | Choice.Yes; +>NoYes : YesNo +>Choice : any +>No : Choice.No +>Choice : any +>Yes : Choice.Yes + +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; +>UnknownYesNo : Choice +>Choice : any +>Unknown : Choice.Unknown +>Choice : any +>Yes : Choice.Yes +>Choice : any +>No : Choice.No + +function f1() { +>f1 : () => void + + var a: YesNo; +>a : YesNo +>YesNo : YesNo + + var a: NoYes; +>a : YesNo +>NoYes : YesNo + + var a: Choice.Yes | Choice.No; +>a : YesNo +>Choice : any +>Yes : Choice.Yes +>Choice : any +>No : Choice.No + + var a: Choice.No | Choice.Yes; +>a : YesNo +>Choice : any +>No : Choice.No +>Choice : any +>Yes : Choice.Yes +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { +>f2 : (a: YesNo, b: Choice, c: Choice) => void +>a : YesNo +>YesNo : YesNo +>b : Choice +>UnknownYesNo : Choice +>c : Choice +>Choice : Choice + + b = a; +>b = a : YesNo +>b : Choice +>a : YesNo + + c = a; +>c = a : YesNo +>c : Choice +>a : YesNo + + c = b; +>c = b : YesNo +>c : Choice +>b : YesNo +} + +function f3(a: Choice.Yes, b: YesNo) { +>f3 : (a: Choice.Yes, b: YesNo) => void +>a : Choice.Yes +>Choice : any +>Yes : Choice.Yes +>b : YesNo +>YesNo : YesNo + + var x = a + b; +>x : string +>a + b : string +>a : Choice.Yes +>b : YesNo + + var y = a == b; +>y : boolean +>a == b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a != b; +>y : boolean +>a != b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a === b; +>y : boolean +>a === b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a !== b; +>y : boolean +>a !== b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a > b; +>y : boolean +>a > b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a < b; +>y : boolean +>a < b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a >= b; +>y : boolean +>a >= b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a <= b; +>y : boolean +>a <= b : boolean +>a : Choice.Yes +>b : YesNo + + var y = !b; +>y : boolean +>!b : false +>b : YesNo +} + +declare function g(x: Choice.Yes): string; +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>x : Choice.Yes +>Choice : any +>Yes : Choice.Yes + +declare function g(x: Choice.No): boolean; +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>x : Choice.No +>Choice : any +>No : Choice.No + +declare function g(x: Choice): number; +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>x : Choice +>Choice : Choice + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { +>f5 : (a: YesNo, b: Choice, c: Choice) => void +>a : YesNo +>YesNo : YesNo +>b : Choice +>UnknownYesNo : Choice +>c : Choice +>Choice : Choice + + var z1 = g(Choice.Yes); +>z1 : string +>g(Choice.Yes) : string +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes + + var z2 = g(Choice.No); +>z2 : boolean +>g(Choice.No) : boolean +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No + + var z3 = g(a); +>z3 : number +>g(a) : number +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>a : YesNo + + var z4 = g(b); +>z4 : number +>g(b) : number +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>b : Choice + + var z5 = g(c); +>z5 : number +>g(c) : number +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>c : Choice +} + +function assertNever(x: never): never { +>assertNever : (x: never) => never +>x : never + + throw new Error("Unexpected value"); +>new Error("Unexpected value") : Error +>Error : ErrorConstructor +>"Unexpected value" : "Unexpected value" +} + +function f10(x: YesNo) { +>f10 : (x: YesNo) => "true" | "false" +>x : YesNo +>YesNo : YesNo + + switch (x) { +>x : YesNo + + case Choice.Yes: return "true"; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>"true" : "true" + + case Choice.No: return "false"; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>"false" : "false" + } +} + +function f11(x: YesNo) { +>f11 : (x: YesNo) => "true" | "false" +>x : YesNo +>YesNo : YesNo + + switch (x) { +>x : YesNo + + case Choice.Yes: return "true"; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>"true" : "true" + + case Choice.No: return "false"; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>"false" : "false" + } + return assertNever(x); +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never +} + +function f12(x: UnknownYesNo) { +>f12 : (x: Choice) => void +>x : Choice +>UnknownYesNo : Choice + + if (x) { +>x : Choice + + x; +>x : YesNo + } + else { + x; +>x : Choice.Unknown + } +} + +function f13(x: UnknownYesNo) { +>f13 : (x: Choice) => void +>x : Choice +>UnknownYesNo : Choice + + if (x === Choice.Yes) { +>x === Choice.Yes : boolean +>x : Choice +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes + + x; +>x : Choice.Yes + } + else { + x; +>x : Choice.Unknown | Choice.No + } +} + +type Item = +>Item : Item + + { kind: Choice.Yes, a: string } | +>kind : Choice.Yes +>Choice : any +>Yes : Choice.Yes +>a : string + + { kind: Choice.No, b: string }; +>kind : Choice.No +>Choice : any +>No : Choice.No +>b : string + +function f20(x: Item) { +>f20 : (x: Item) => string +>x : Item +>Item : Item + + switch (x.kind) { +>x.kind : YesNo +>x : Item +>kind : YesNo + + case Choice.Yes: return x.a; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>x.a : string +>x : { kind: Choice.Yes; a: string; } +>a : string + + case Choice.No: return x.b; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>x.b : string +>x : { kind: Choice.No; b: string; } +>b : string + } +} + +function f21(x: Item) { +>f21 : (x: Item) => string +>x : Item +>Item : Item + + switch (x.kind) { +>x.kind : YesNo +>x : Item +>kind : YesNo + + case Choice.Yes: return x.a; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>x.a : string +>x : { kind: Choice.Yes; a: string; } +>a : string + + case Choice.No: return x.b; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>x.b : string +>x : { kind: Choice.No; b: string; } +>b : string + } + return assertNever(x); +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never +} diff --git a/tests/baselines/reference/stringEnumLiteralTypes3.errors.txt b/tests/baselines/reference/stringEnumLiteralTypes3.errors.txt new file mode 100644 index 00000000000..7feed87d824 --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes3.errors.txt @@ -0,0 +1,166 @@ +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(10,5): error TS2322: Type 'YesNo' is not assignable to type 'Choice.Yes'. + Type 'Choice.No' is not assignable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(11,5): error TS2322: Type 'Choice' is not assignable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(12,5): error TS2322: Type 'Choice' is not assignable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(18,5): error TS2322: Type 'Choice' is not assignable to type 'YesNo'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(19,5): error TS2322: Type 'Choice' is not assignable to type 'YesNo'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(37,5): error TS2322: Type 'Choice.Unknown' is not assignable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(39,5): error TS2322: Type 'Choice.No' is not assignable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(40,5): error TS2322: Type 'Choice.Unknown' is not assignable to type 'YesNo'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(52,5): error TS2365: Operator '===' cannot be applied to types 'Choice.Yes' and 'Choice.Unknown'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(54,5): error TS2365: Operator '===' cannot be applied to types 'Choice.Yes' and 'Choice.No'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(55,5): error TS2365: Operator '===' cannot be applied to types 'YesNo' and 'Choice.Unknown'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(87,14): error TS2678: Type 'Choice.Unknown' is not comparable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(89,14): error TS2678: Type 'Choice.No' is not comparable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(96,14): error TS2678: Type 'Choice.Unknown' is not comparable to type 'YesNo'. + + +==== tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts (14 errors) ==== + const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + + type Yes = Choice.Yes; + type YesNo = Choice.Yes | Choice.No; + type NoYes = Choice.No | Choice.Yes; + type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + + function f1(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a = a; + a = b; + ~ +!!! error TS2322: Type 'YesNo' is not assignable to type 'Choice.Yes'. +!!! error TS2322: Type 'Choice.No' is not assignable to type 'Choice.Yes'. + a = c; + ~ +!!! error TS2322: Type 'Choice' is not assignable to type 'Choice.Yes'. + a = d; + ~ +!!! error TS2322: Type 'Choice' is not assignable to type 'Choice.Yes'. + } + + function f2(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + b = a; + b = b; + b = c; + ~ +!!! error TS2322: Type 'Choice' is not assignable to type 'YesNo'. + b = d; + ~ +!!! error TS2322: Type 'Choice' is not assignable to type 'YesNo'. + } + + function f3(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + c = a; + c = b; + c = c; + c = d; + } + + function f4(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + d = a; + d = b; + d = c; + d = d; + } + + function f5(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a = Choice.Unknown; + ~ +!!! error TS2322: Type 'Choice.Unknown' is not assignable to type 'Choice.Yes'. + a = Choice.Yes; + a = Choice.No; + ~ +!!! error TS2322: Type 'Choice.No' is not assignable to type 'Choice.Yes'. + b = Choice.Unknown; + ~ +!!! error TS2322: Type 'Choice.Unknown' is not assignable to type 'YesNo'. + b = Choice.Yes; + b = Choice.No; + c = Choice.Unknown; + c = Choice.Yes; + c = Choice.No; + d = Choice.Unknown; + d = Choice.Yes; + d = Choice.No; + } + + function f6(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a === Choice.Unknown; + ~~~~~~~~~~~~~~~~~~~~ +!!! error TS2365: Operator '===' cannot be applied to types 'Choice.Yes' and 'Choice.Unknown'. + a === Choice.Yes; + a === Choice.No; + ~~~~~~~~~~~~~~~ +!!! error TS2365: Operator '===' cannot be applied to types 'Choice.Yes' and 'Choice.No'. + b === Choice.Unknown; + ~~~~~~~~~~~~~~~~~~~~ +!!! error TS2365: Operator '===' cannot be applied to types 'YesNo' and 'Choice.Unknown'. + b === Choice.Yes; + b === Choice.No; + c === Choice.Unknown; + c === Choice.Yes; + c === Choice.No; + d === Choice.Unknown; + d === Choice.Yes; + d === Choice.No; + } + + function f7(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a === a; + a === b; + a === c; + a === d; + b === a; + b === b; + b === c; + b === d; + c === a; + c === b; + c === c; + c === d; + d === a; + d === b; + d === c; + d === d; + } + + function f10(x: Yes): Yes { + switch (x) { + case Choice.Unknown: return x; + ~~~~~~~~~~~~~~ +!!! error TS2678: Type 'Choice.Unknown' is not comparable to type 'Choice.Yes'. + case Choice.Yes: return x; + case Choice.No: return x; + ~~~~~~~~~ +!!! error TS2678: Type 'Choice.No' is not comparable to type 'Choice.Yes'. + } + return x; + } + + function f11(x: YesNo): YesNo { + switch (x) { + case Choice.Unknown: return x; + ~~~~~~~~~~~~~~ +!!! error TS2678: Type 'Choice.Unknown' is not comparable to type 'YesNo'. + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; + } + + function f12(x: UnknownYesNo): UnknownYesNo { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; + } + + function f13(x: Choice): Choice { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; + } \ No newline at end of file diff --git a/tests/baselines/reference/stringEnumLiteralTypes3.js b/tests/baselines/reference/stringEnumLiteralTypes3.js new file mode 100644 index 00000000000..7e2699460b2 --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes3.js @@ -0,0 +1,225 @@ +//// [stringEnumLiteralTypes3.ts] +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + +type Yes = Choice.Yes; +type YesNo = Choice.Yes | Choice.No; +type NoYes = Choice.No | Choice.Yes; +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + +function f1(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a = a; + a = b; + a = c; + a = d; +} + +function f2(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + b = a; + b = b; + b = c; + b = d; +} + +function f3(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + c = a; + c = b; + c = c; + c = d; +} + +function f4(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + d = a; + d = b; + d = c; + d = d; +} + +function f5(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a = Choice.Unknown; + a = Choice.Yes; + a = Choice.No; + b = Choice.Unknown; + b = Choice.Yes; + b = Choice.No; + c = Choice.Unknown; + c = Choice.Yes; + c = Choice.No; + d = Choice.Unknown; + d = Choice.Yes; + d = Choice.No; +} + +function f6(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a === Choice.Unknown; + a === Choice.Yes; + a === Choice.No; + b === Choice.Unknown; + b === Choice.Yes; + b === Choice.No; + c === Choice.Unknown; + c === Choice.Yes; + c === Choice.No; + d === Choice.Unknown; + d === Choice.Yes; + d === Choice.No; +} + +function f7(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a === a; + a === b; + a === c; + a === d; + b === a; + b === b; + b === c; + b === d; + c === a; + c === b; + c === c; + c === d; + d === a; + d === b; + d === c; + d === d; +} + +function f10(x: Yes): Yes { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +function f11(x: YesNo): YesNo { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +function f12(x: UnknownYesNo): UnknownYesNo { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +function f13(x: Choice): Choice { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +//// [stringEnumLiteralTypes3.js] +; +function f1(a, b, c, d) { + a = a; + a = b; + a = c; + a = d; +} +function f2(a, b, c, d) { + b = a; + b = b; + b = c; + b = d; +} +function f3(a, b, c, d) { + c = a; + c = b; + c = c; + c = d; +} +function f4(a, b, c, d) { + d = a; + d = b; + d = c; + d = d; +} +function f5(a, b, c, d) { + a = "" /* Unknown */; + a = "yes" /* Yes */; + a = "no" /* No */; + b = "" /* Unknown */; + b = "yes" /* Yes */; + b = "no" /* No */; + c = "" /* Unknown */; + c = "yes" /* Yes */; + c = "no" /* No */; + d = "" /* Unknown */; + d = "yes" /* Yes */; + d = "no" /* No */; +} +function f6(a, b, c, d) { + a === "" /* Unknown */; + a === "yes" /* Yes */; + a === "no" /* No */; + b === "" /* Unknown */; + b === "yes" /* Yes */; + b === "no" /* No */; + c === "" /* Unknown */; + c === "yes" /* Yes */; + c === "no" /* No */; + d === "" /* Unknown */; + d === "yes" /* Yes */; + d === "no" /* No */; +} +function f7(a, b, c, d) { + a === a; + a === b; + a === c; + a === d; + b === a; + b === b; + b === c; + b === d; + c === a; + c === b; + c === c; + c === d; + d === a; + d === b; + d === c; + d === d; +} +function f10(x) { + switch (x) { + case "" /* Unknown */: return x; + case "yes" /* Yes */: return x; + case "no" /* No */: return x; + } + return x; +} +function f11(x) { + switch (x) { + case "" /* Unknown */: return x; + case "yes" /* Yes */: return x; + case "no" /* No */: return x; + } + return x; +} +function f12(x) { + switch (x) { + case "" /* Unknown */: return x; + case "yes" /* Yes */: return x; + case "no" /* No */: return x; + } + return x; +} +function f13(x) { + switch (x) { + case "" /* Unknown */: return x; + case "yes" /* Yes */: return x; + case "no" /* No */: return x; + } + return x; +} diff --git a/tests/baselines/reference/subtypesOfUnion.errors.txt b/tests/baselines/reference/subtypesOfUnion.errors.txt index fade5377814..7cbca6cc409 100644 --- a/tests/baselines/reference/subtypesOfUnion.errors.txt +++ b/tests/baselines/reference/subtypesOfUnion.errors.txt @@ -12,21 +12,21 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOf tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(28,5): error TS2411: Property 'foo16' of type 'T' is not assignable to string index type 'string | number'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(29,5): error TS2411: Property 'foo17' of type 'Object' is not assignable to string index type 'string | number'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(30,5): error TS2411: Property 'foo18' of type '{}' is not assignable to string index type 'string | number'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(35,5): error TS2411: Property 'foo2' of type 'string' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(37,5): error TS2411: Property 'foo4' of type 'boolean' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(39,5): error TS2411: Property 'foo6' of type 'Date' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(40,5): error TS2411: Property 'foo7' of type 'RegExp' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(41,5): error TS2411: Property 'foo8' of type '{ bar: number; }' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(42,5): error TS2411: Property 'foo9' of type 'I8' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(43,5): error TS2411: Property 'foo10' of type 'A' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(44,5): error TS2411: Property 'foo11' of type 'A2' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(45,5): error TS2411: Property 'foo12' of type '(x: any) => number' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(46,5): error TS2411: Property 'foo13' of type '(x: T) => T' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(47,5): error TS2411: Property 'foo14' of type 'typeof f' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(48,5): error TS2411: Property 'foo15' of type 'typeof c' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(49,5): error TS2411: Property 'foo16' of type 'T' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(50,5): error TS2411: Property 'foo17' of type 'Object' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(51,5): error TS2411: Property 'foo18' of type '{}' is not assignable to string index type 'number | E'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(35,5): error TS2411: Property 'foo2' of type 'string' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(37,5): error TS2411: Property 'foo4' of type 'boolean' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(39,5): error TS2411: Property 'foo6' of type 'Date' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(40,5): error TS2411: Property 'foo7' of type 'RegExp' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(41,5): error TS2411: Property 'foo8' of type '{ bar: number; }' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(42,5): error TS2411: Property 'foo9' of type 'I8' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(43,5): error TS2411: Property 'foo10' of type 'A' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(44,5): error TS2411: Property 'foo11' of type 'A2' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(45,5): error TS2411: Property 'foo12' of type '(x: any) => number' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(46,5): error TS2411: Property 'foo13' of type '(x: T) => T' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(47,5): error TS2411: Property 'foo14' of type 'typeof f' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(48,5): error TS2411: Property 'foo15' of type 'typeof c' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(49,5): error TS2411: Property 'foo16' of type 'T' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(50,5): error TS2411: Property 'foo17' of type 'Object' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(51,5): error TS2411: Property 'foo18' of type '{}' is not assignable to string index type 'number'. ==== tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts (29 errors) ==== @@ -94,49 +94,49 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOf foo: any; // ok foo2: string; // error ~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'string' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo2' of type 'string' is not assignable to string index type 'number'. foo3: number; // ok foo4: boolean; // error ~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo4' of type 'boolean' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo4' of type 'boolean' is not assignable to string index type 'number'. foo5: E; // ok foo6: Date; // error ~~~~~~~~~~~ -!!! error TS2411: Property 'foo6' of type 'Date' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo6' of type 'Date' is not assignable to string index type 'number'. foo7: RegExp; // error ~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo7' of type 'RegExp' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo7' of type 'RegExp' is not assignable to string index type 'number'. foo8: { bar: number }; // error ~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo8' of type '{ bar: number; }' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo8' of type '{ bar: number; }' is not assignable to string index type 'number'. foo9: I8; // error ~~~~~~~~~ -!!! error TS2411: Property 'foo9' of type 'I8' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo9' of type 'I8' is not assignable to string index type 'number'. foo10: A; // error ~~~~~~~~~ -!!! error TS2411: Property 'foo10' of type 'A' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo10' of type 'A' is not assignable to string index type 'number'. foo11: A2; // error ~~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo11' of type 'A2' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo11' of type 'A2' is not assignable to string index type 'number'. foo12: (x) => number; //error ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo12' of type '(x: any) => number' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo12' of type '(x: any) => number' is not assignable to string index type 'number'. foo13: (x: T) => T; // error ~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo13' of type '(x: T) => T' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo13' of type '(x: T) => T' is not assignable to string index type 'number'. foo14: typeof f; // error ~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo14' of type 'typeof f' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo14' of type 'typeof f' is not assignable to string index type 'number'. foo15: typeof c; // error ~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo15' of type 'typeof c' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo15' of type 'typeof c' is not assignable to string index type 'number'. foo16: T; // error ~~~~~~~~~ -!!! error TS2411: Property 'foo16' of type 'T' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo16' of type 'T' is not assignable to string index type 'number'. foo17: Object; // error ~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo17' of type 'Object' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo17' of type 'Object' is not assignable to string index type 'number'. foo18: {}; // error ~~~~~~~~~~ -!!! error TS2411: Property 'foo18' of type '{}' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo18' of type '{}' is not assignable to string index type 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/switchStatementsWithMultipleDefaults.js b/tests/baselines/reference/switchStatementsWithMultipleDefaults.js index e65e10a0c99..e41d8c016ef 100644 --- a/tests/baselines/reference/switchStatementsWithMultipleDefaults.js +++ b/tests/baselines/reference/switchStatementsWithMultipleDefaults.js @@ -35,7 +35,7 @@ var x = 10; switch (x) { case 1: case 2: - default: + default:// No issues. break; default: // Error; second 'default' clause. default: // Error; third 'default' clause. @@ -43,12 +43,12 @@ switch (x) { x *= x; } switch (x) { - default: + default:// No issues. break; case 100: switch (x * x) { default: // No issues. - default: + default:// Error; second 'default' clause. break; case 10000: x /= x; diff --git a/tests/baselines/reference/switchStatementsWithMultipleDefaults1.js b/tests/baselines/reference/switchStatementsWithMultipleDefaults1.js index 2d52dd761cc..d733ce38a7b 100644 --- a/tests/baselines/reference/switchStatementsWithMultipleDefaults1.js +++ b/tests/baselines/reference/switchStatementsWithMultipleDefaults1.js @@ -17,7 +17,7 @@ var x = 10; switch (x) { case 1: case 2: - default: + default:// No issues. break; default: // Error; second 'default' clause. default: // Error; third 'default' clause. diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.errors.txt index e9c9e0ed6e0..109312d6264 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.errors.txt @@ -4,9 +4,9 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(11,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(12,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(13,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(14,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(14,9): error TS2554: Expected 1-3 arguments, but got 4. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(19,20): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(21,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(21,9): error TS2554: Expected 1-3 arguments, but got 4. ==== tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts (8 errors) ==== @@ -36,7 +36,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio !!! error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. var f = foo([], 1, 2, 3); // any (with error) ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-3 arguments, but got 4. var u = foo ``; // number var v = foo `${1}`; // string @@ -47,5 +47,5 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio var y = foo `${1}${"2"}`; // {} var z = foo `${1}${2}${3}`; // any (with error) ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-3 arguments, but got 4. \ No newline at end of file diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1_ES6.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1_ES6.errors.txt index d7817e32ee0..0d2cafea7b3 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1_ES6.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1_ES6.errors.txt @@ -4,9 +4,9 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(11,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(12,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(13,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(14,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(14,9): error TS2554: Expected 1-3 arguments, but got 4. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(19,20): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(21,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(21,9): error TS2554: Expected 1-3 arguments, but got 4. ==== tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts (8 errors) ==== @@ -36,7 +36,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio !!! error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. var f = foo([], 1, 2, 3); // any (with error) ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-3 arguments, but got 4. var u = foo ``; // number var v = foo `${1}`; // string @@ -47,5 +47,5 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio var y = foo `${1}${"2"}`; // {} var z = foo `${1}${2}${3}`; // any (with error) ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-3 arguments, but got 4. \ No newline at end of file diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt index 444985cb380..e7fb6ea1241 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(9,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(18,4): error TS2339: Property 'foo' does not exist on type 'Date'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(44,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(44,1): error TS2554: Expected 2-4 arguments, but got 1. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(62,9): error TS2345: Argument of type 'true' is not assignable to parameter of type 'number'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(63,18): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(69,18): error TS2339: Property 'toFixed' does not exist on type 'string'. @@ -56,7 +56,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio // Generic overloads with differing arity tagging with argument count that doesn't match any overload fn3 ``; // Error ~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2-4 arguments, but got 1. // Generic overloads with constraints function fn4(strs: TemplateStringsArray, n: T, m: U); diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt index 7329ade1b64..d41d64c5a28 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(9,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(18,4): error TS2339: Property 'foo' does not exist on type 'Date'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(44,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(44,1): error TS2554: Expected 2-4 arguments, but got 1. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(62,9): error TS2345: Argument of type 'true' is not assignable to parameter of type 'number'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(63,18): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(69,18): error TS2339: Property 'toFixed' does not exist on type 'string'. @@ -56,7 +56,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio // Generic overloads with differing arity tagging with argument count that doesn't match any overload fn3 ``; // Error ~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2-4 arguments, but got 1. // Generic overloads with constraints function fn4(strs: TemplateStringsArray, n: T, m: U); diff --git a/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions4.errors.txt b/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions4.errors.txt index cc499cb2578..71066aec61f 100644 --- a/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions4.errors.txt +++ b/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,1): error TS2554: Expected 3 arguments, but got 4. tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,24): error TS1109: Expression expected. tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,28): error TS1109: Expression expected. @@ -10,7 +10,7 @@ tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,28): // Incomplete call, but too many parameters. f `123qdawdrqw${ 1 }${ }${ ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 3 arguments, but got 4. ~ !!! error TS1109: Expression expected. diff --git a/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions5.errors.txt b/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions5.errors.txt index 0a4f0724cc2..e18bafa9149 100644 --- a/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions5.errors.txt +++ b/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions5.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions5.ts(5,1): error TS2554: Expected 3 arguments, but got 4. tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions5.ts(5,30): error TS1109: Expression expected. @@ -9,6 +9,6 @@ tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions5.ts(5,30): // Incomplete call, but too many parameters. f `123qdawdrqw${ 1 }${ 2 }${ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 3 arguments, but got 4. !!! error TS1109: Expression expected. \ No newline at end of file diff --git a/tests/baselines/reference/thisExpressionInCallExpressionWithTypeArguments.errors.txt b/tests/baselines/reference/thisExpressionInCallExpressionWithTypeArguments.errors.txt index 6f60a8f1be7..5288875b0ce 100644 --- a/tests/baselines/reference/thisExpressionInCallExpressionWithTypeArguments.errors.txt +++ b/tests/baselines/reference/thisExpressionInCallExpressionWithTypeArguments.errors.txt @@ -1,10 +1,10 @@ -tests/cases/compiler/thisExpressionInCallExpressionWithTypeArguments.ts(2,20): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/thisExpressionInCallExpressionWithTypeArguments.ts(2,20): error TS2554: Expected 1-2 arguments, but got 1. ==== tests/cases/compiler/thisExpressionInCallExpressionWithTypeArguments.ts (1 errors) ==== class C { public foo() { [1,2,3].map((x) => { return this; })} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 1. } \ No newline at end of file diff --git a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt index e88f4c1ca96..ad8978847f4 100644 --- a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt +++ b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt @@ -10,26 +10,26 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(62,97): er Object literal may only specify known properties, and 'explicitStructural' does not exist in type '{ y: string; f: (this: { y: number; }, x: number) => number; }'. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(63,110): error TS2322: Type '{ wrongName: number; explicitStructural: (this: { y: number; }, x: number) => number; }' is not assignable to type '{ wrongName: number; f: (this: { y: number; }, x: number) => number; }'. Object literal may only specify known properties, and 'explicitStructural' does not exist in type '{ wrongName: number; f: (this: { y: number; }, x: number) => number; }'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(65,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(65,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(66,6): error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(67,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(67,1): error TS2554: Expected 1 arguments, but got 2. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(68,1): error TS2684: The 'this' context of type '{ y: string; f: (this: { y: number; }, x: number) => number; }' is not assignable to method's 'this' of type '{ y: number; }'. Types of property 'y' are incompatible. Type 'string' is not assignable to type 'number'. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(69,1): error TS2684: The 'this' context of type '{ wrongName: number; f: (this: { y: number; }, x: number) => number; }' is not assignable to method's 'this' of type '{ y: number; }'. Property 'y' is missing in type '{ wrongName: number; f: (this: { y: number; }, x: number) => number; }'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(72,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(72,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(73,13): error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(74,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(75,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(74,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(75,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(76,16): error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(77,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(78,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(77,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(78,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(79,16): error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(80,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(81,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(80,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(81,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(82,20): error TS2345: Argument of type '"wrong type 3"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(83,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(83,1): error TS2554: Expected 1 arguments, but got 2. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(86,5): error TS2322: Type '(this: { y: number; }, x: number) => number' is not assignable to type '(this: void, x: number) => number'. The 'this' types of each signature are incompatible. Type 'void' is not assignable to type '{ y: number; }'. @@ -91,7 +91,7 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,30): e tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,32): error TS1138: Parameter declaration expected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,39): error TS1005: ';' expected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,40): error TS1128: Declaration or statement expected. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,42): error TS2304: Cannot find name 'number'. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,42): error TS2693: 'number' only refers to a type, but is being used as a value here. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,49): error TS1005: ';' expected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,1): error TS7027: Unreachable code detected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,29): error TS2304: Cannot find name 'm'. @@ -187,13 +187,13 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,35): e ok.f(); // not enough arguments ~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. ok.f('wrong type'); ~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. ok.f(13, 'too many arguments'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. wrongPropertyType.f(13); ~~~~~~~~~~~~~~~~~ !!! error TS2684: The 'this' context of type '{ y: string; f: (this: { y: number; }, x: number) => number; }' is not assignable to method's 'this' of type '{ y: number; }'. @@ -207,40 +207,40 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,35): e let c = new C(); c.explicitC(); // not enough arguments ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. c.explicitC('wrong type'); ~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. c.explicitC(13, 'too many arguments'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. c.explicitThis(); // not enough arguments ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. c.explicitThis('wrong type 2'); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. c.explicitThis(14, 'too many arguments 2'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. c.implicitThis(); // not enough arguments ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. c.implicitThis('wrong type 2'); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. c.implicitThis(14, 'too many arguments 2'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. c.explicitProperty(); // not enough arguments ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. c.explicitProperty('wrong type 3'); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type 3"' is not assignable to parameter of type 'number'. c.explicitProperty(15, 'too many arguments 3'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. // oops, this triggers contextual typing, which needs to be updated to understand that =>'s `this` is void. let specifiedToVoid: (this: void, x: number) => number = explicitStructural; @@ -425,7 +425,7 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,35): e ~ !!! error TS1128: Declaration or statement expected. ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. diff --git a/tests/baselines/reference/tooManyTypeParameters1.errors.txt b/tests/baselines/reference/tooManyTypeParameters1.errors.txt index 2355ef55e56..7997e68b575 100644 --- a/tests/baselines/reference/tooManyTypeParameters1.errors.txt +++ b/tests/baselines/reference/tooManyTypeParameters1.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/tooManyTypeParameters1.ts(2,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/tooManyTypeParameters1.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/tooManyTypeParameters1.ts(8,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/tooManyTypeParameters1.ts(2,1): error TS2558: Expected 1 type arguments, but got 2. +tests/cases/compiler/tooManyTypeParameters1.ts(5,1): error TS2558: Expected 1 type arguments, but got 2. +tests/cases/compiler/tooManyTypeParameters1.ts(8,9): error TS2558: Expected 1 type arguments, but got 2. tests/cases/compiler/tooManyTypeParameters1.ts(11,8): error TS2314: Generic type 'I' requires 1 type argument(s). @@ -8,17 +8,17 @@ tests/cases/compiler/tooManyTypeParameters1.ts(11,8): error TS2314: Generic type function f() { } f(); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 1 type arguments, but got 2. var x = () => {}; x(); ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 1 type arguments, but got 2. class C {} var c = new C(); ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 1 type arguments, but got 2. interface I {} var i: I; diff --git a/tests/baselines/reference/tsxAttributeResolution1.errors.txt b/tests/baselines/reference/tsxAttributeResolution1.errors.txt index d064f72f85d..f6c84f80fa5 100644 --- a/tests/baselines/reference/tsxAttributeResolution1.errors.txt +++ b/tests/baselines/reference/tsxAttributeResolution1.errors.txt @@ -1,15 +1,12 @@ tests/cases/conformance/jsx/file.tsx(23,8): error TS2322: Type '{ x: "0"; }' is not assignable to type 'Attribs1'. Types of property 'x' are incompatible. Type '"0"' is not assignable to type 'number'. -tests/cases/conformance/jsx/file.tsx(24,8): error TS2322: Type '{ y: 0; }' is not assignable to type 'Attribs1'. - Property 'y' does not exist on type 'Attribs1'. -tests/cases/conformance/jsx/file.tsx(25,8): error TS2322: Type '{ y: "foo"; }' is not assignable to type 'Attribs1'. - Property 'y' does not exist on type 'Attribs1'. +tests/cases/conformance/jsx/file.tsx(24,8): error TS2339: Property 'y' does not exist on type 'Attribs1'. +tests/cases/conformance/jsx/file.tsx(25,8): error TS2339: Property 'y' does not exist on type 'Attribs1'. tests/cases/conformance/jsx/file.tsx(26,8): error TS2322: Type '{ x: "32"; }' is not assignable to type 'Attribs1'. Types of property 'x' are incompatible. Type '"32"' is not assignable to type 'number'. -tests/cases/conformance/jsx/file.tsx(27,8): error TS2322: Type '{ var: "10"; }' is not assignable to type 'Attribs1'. - Property 'var' does not exist on type 'Attribs1'. +tests/cases/conformance/jsx/file.tsx(27,8): error TS2339: Property 'var' does not exist on type 'Attribs1'. tests/cases/conformance/jsx/file.tsx(29,1): error TS2322: Type '{}' is not assignable to type '{ reqd: string; }'. Property 'reqd' is missing in type '{}'. tests/cases/conformance/jsx/file.tsx(30,8): error TS2322: Type '{ reqd: 10; }' is not assignable to type '{ reqd: string; }'. @@ -47,12 +44,10 @@ tests/cases/conformance/jsx/file.tsx(30,8): error TS2322: Type '{ reqd: 10; }' i !!! error TS2322: Type '"0"' is not assignable to type 'number'. ; // Error, no property "y" ~~~~~ -!!! error TS2322: Type '{ y: 0; }' is not assignable to type 'Attribs1'. -!!! error TS2322: Property 'y' does not exist on type 'Attribs1'. +!!! error TS2339: Property 'y' does not exist on type 'Attribs1'. ; // Error, no property "y" ~~~~~~~ -!!! error TS2322: Type '{ y: "foo"; }' is not assignable to type 'Attribs1'. -!!! error TS2322: Property 'y' does not exist on type 'Attribs1'. +!!! error TS2339: Property 'y' does not exist on type 'Attribs1'. ; // Error, "32" is not number ~~~~~~ !!! error TS2322: Type '{ x: "32"; }' is not assignable to type 'Attribs1'. @@ -60,8 +55,7 @@ tests/cases/conformance/jsx/file.tsx(30,8): error TS2322: Type '{ reqd: 10; }' i !!! error TS2322: Type '"32"' is not assignable to type 'number'. ; // Error, no 'var' property ~~~~~~~~ -!!! error TS2322: Type '{ var: "10"; }' is not assignable to type 'Attribs1'. -!!! error TS2322: Property 'var' does not exist on type 'Attribs1'. +!!! error TS2339: Property 'var' does not exist on type 'Attribs1'. ; // Error, missing reqd ~~~~~~~~~ diff --git a/tests/baselines/reference/tsxAttributeResolution11.errors.txt b/tests/baselines/reference/tsxAttributeResolution11.errors.txt index 08a75c3b8bb..907b9bce776 100644 --- a/tests/baselines/reference/tsxAttributeResolution11.errors.txt +++ b/tests/baselines/reference/tsxAttributeResolution11.errors.txt @@ -1,5 +1,4 @@ -tests/cases/conformance/jsx/file.tsx(11,22): error TS2322: Type '{ bar: "world"; }' is not assignable to type 'IntrinsicAttributes & { ref?: string; }'. - Property 'bar' does not exist on type 'IntrinsicAttributes & { ref?: string; }'. +tests/cases/conformance/jsx/file.tsx(11,22): error TS2339: Property 'bar' does not exist on type 'IntrinsicAttributes & { ref?: string; }'. ==== tests/cases/conformance/jsx/react.d.ts (0 errors) ==== @@ -28,7 +27,6 @@ tests/cases/conformance/jsx/file.tsx(11,22): error TS2322: Type '{ bar: "world"; // Should be an OK var x = ; ~~~~~~~~~~~ -!!! error TS2322: Type '{ bar: "world"; }' is not assignable to type 'IntrinsicAttributes & { ref?: string; }'. -!!! error TS2322: Property 'bar' does not exist on type 'IntrinsicAttributes & { ref?: string; }'. +!!! error TS2339: Property 'bar' does not exist on type 'IntrinsicAttributes & { ref?: string; }'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxAttributeResolution15.errors.txt b/tests/baselines/reference/tsxAttributeResolution15.errors.txt index 870599acd27..2ab79ea7aae 100644 --- a/tests/baselines/reference/tsxAttributeResolution15.errors.txt +++ b/tests/baselines/reference/tsxAttributeResolution15.errors.txt @@ -1,5 +1,4 @@ -tests/cases/conformance/jsx/file.tsx(11,21): error TS2322: Type '{ prop1: "hello"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. - Property 'prop1' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. +tests/cases/conformance/jsx/file.tsx(11,21): error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. ==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== @@ -15,8 +14,7 @@ tests/cases/conformance/jsx/file.tsx(11,21): error TS2322: Type '{ prop1: "hello // Error let a = ~~~~~~~~~~~~~ -!!! error TS2322: Type '{ prop1: "hello"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. -!!! error TS2322: Property 'prop1' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. +!!! error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. // OK let b = { this.textInput = input; }} /> diff --git a/tests/baselines/reference/tsxAttributeResolution3.errors.txt b/tests/baselines/reference/tsxAttributeResolution3.errors.txt index d5517ea31a2..b4ec56c0c46 100644 --- a/tests/baselines/reference/tsxAttributeResolution3.errors.txt +++ b/tests/baselines/reference/tsxAttributeResolution3.errors.txt @@ -6,11 +6,9 @@ tests/cases/conformance/jsx/file.tsx(23,8): error TS2322: Type '{ y: number; }' tests/cases/conformance/jsx/file.tsx(31,8): error TS2322: Type '{ x: number; y: number; }' is not assignable to type 'Attribs1'. Types of property 'x' are incompatible. Type 'number' is not assignable to type 'string'. -tests/cases/conformance/jsx/file.tsx(35,8): error TS2322: Type '{ x: string; y: number; extra: number; }' is not assignable to type 'Attribs1'. - Property 'extra' does not exist on type 'Attribs1'. -==== tests/cases/conformance/jsx/file.tsx (4 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== declare module JSX { interface Element { } interface IntrinsicElements { @@ -54,12 +52,9 @@ tests/cases/conformance/jsx/file.tsx(35,8): error TS2322: Type '{ x: string; y: !!! error TS2322: Types of property 'x' are incompatible. !!! error TS2322: Type 'number' is not assignable to type 'string'. - // Error + // Ok var obj6 = { x: 'ok', y: 32, extra: 100 }; - ~~~~~~~~~ -!!! error TS2322: Type '{ x: string; y: number; extra: number; }' is not assignable to type 'Attribs1'. -!!! error TS2322: Property 'extra' does not exist on type 'Attribs1'. // OK (spread override) var obj7 = { x: 'foo' }; diff --git a/tests/baselines/reference/tsxAttributeResolution3.js b/tests/baselines/reference/tsxAttributeResolution3.js index c96fd77e284..692fb4ba0b9 100644 --- a/tests/baselines/reference/tsxAttributeResolution3.js +++ b/tests/baselines/reference/tsxAttributeResolution3.js @@ -31,7 +31,7 @@ var obj4 = { x: 32, y: 32 }; var obj5 = { x: 32, y: 32 }; -// Error +// Ok var obj6 = { x: 'ok', y: 32, extra: 100 }; @@ -56,7 +56,7 @@ var obj4 = { x: 32, y: 32 }; // Error var obj5 = { x: 32, y: 32 }; ; -// Error +// Ok var obj6 = { x: 'ok', y: 32, extra: 100 }; ; // OK (spread override) diff --git a/tests/baselines/reference/tsxAttributeResolution5.errors.txt b/tests/baselines/reference/tsxAttributeResolution5.errors.txt index ffbd41a07b2..f5af99d6f07 100644 --- a/tests/baselines/reference/tsxAttributeResolution5.errors.txt +++ b/tests/baselines/reference/tsxAttributeResolution5.errors.txt @@ -1,11 +1,15 @@ -tests/cases/conformance/jsx/file.tsx(17,16): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(21,16): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(25,16): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/jsx/file.tsx(21,16): error TS2322: Type 'T' is not assignable to type 'Attribs1'. + Type '{ x: number; }' is not assignable to type 'Attribs1'. + Types of property 'x' are incompatible. + Type 'number' is not assignable to type 'string'. +tests/cases/conformance/jsx/file.tsx(25,16): error TS2322: Type 'T' is not assignable to type 'Attribs1'. + Type '{ y: string; }' is not assignable to type 'Attribs1'. + Property 'x' is missing in type '{ y: string; }'. tests/cases/conformance/jsx/file.tsx(29,8): error TS2322: Type '{}' is not assignable to type 'Attribs1'. Property 'x' is missing in type '{}'. -==== tests/cases/conformance/jsx/file.tsx (4 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== declare module JSX { interface Element { } interface IntrinsicElements { @@ -23,20 +27,23 @@ tests/cases/conformance/jsx/file.tsx(29,8): error TS2322: Type '{}' is not assig function make1 (obj: T) { return ; // OK - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. } function make2 (obj: T) { return ; // Error (x is number, not string) ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. +!!! error TS2322: Type 'T' is not assignable to type 'Attribs1'. +!!! error TS2322: Type '{ x: number; }' is not assignable to type 'Attribs1'. +!!! error TS2322: Types of property 'x' are incompatible. +!!! error TS2322: Type 'number' is not assignable to type 'string'. } function make3 (obj: T) { return ; // Error, missing x ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. +!!! error TS2322: Type 'T' is not assignable to type 'Attribs1'. +!!! error TS2322: Type '{ y: string; }' is not assignable to type 'Attribs1'. +!!! error TS2322: Property 'x' is missing in type '{ y: string; }'. } diff --git a/tests/baselines/reference/tsxElementResolution11.errors.txt b/tests/baselines/reference/tsxElementResolution11.errors.txt index f0d5cf1e009..878f5a8b337 100644 --- a/tests/baselines/reference/tsxElementResolution11.errors.txt +++ b/tests/baselines/reference/tsxElementResolution11.errors.txt @@ -1,5 +1,4 @@ -tests/cases/conformance/jsx/file.tsx(17,7): error TS2322: Type '{ x: 10; }' is not assignable to type '{ q?: number; }'. - Property 'x' does not exist on type '{ q?: number; }'. +tests/cases/conformance/jsx/file.tsx(17,7): error TS2339: Property 'x' does not exist on type '{ q?: number; }'. ==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== @@ -21,8 +20,7 @@ tests/cases/conformance/jsx/file.tsx(17,7): error TS2322: Type '{ x: 10; }' is n var Obj2: Obj2type; ; // Error ~~~~~~ -!!! error TS2322: Type '{ x: 10; }' is not assignable to type '{ q?: number; }'. -!!! error TS2322: Property 'x' does not exist on type '{ q?: number; }'. +!!! error TS2339: Property 'x' does not exist on type '{ q?: number; }'. interface Obj3type { new(n: string): { x: number; }; diff --git a/tests/baselines/reference/tsxElementResolution3.errors.txt b/tests/baselines/reference/tsxElementResolution3.errors.txt index d869821a4cb..4e7687c94e2 100644 --- a/tests/baselines/reference/tsxElementResolution3.errors.txt +++ b/tests/baselines/reference/tsxElementResolution3.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/jsx/file.tsx(12,7): error TS2322: Type '{ w: "err"; }' is not assignable to type '{ n: string; }'. - Property 'w' does not exist on type '{ n: string; }'. + Property 'n' is missing in type '{ w: "err"; }'. ==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== @@ -17,4 +17,4 @@ tests/cases/conformance/jsx/file.tsx(12,7): error TS2322: Type '{ w: "err"; }' i ; ~~~~~~~ !!! error TS2322: Type '{ w: "err"; }' is not assignable to type '{ n: string; }'. -!!! error TS2322: Property 'w' does not exist on type '{ n: string; }'. \ No newline at end of file +!!! error TS2322: Property 'n' is missing in type '{ w: "err"; }'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxElementResolution4.errors.txt b/tests/baselines/reference/tsxElementResolution4.errors.txt index b5d5437d872..461cfe025df 100644 --- a/tests/baselines/reference/tsxElementResolution4.errors.txt +++ b/tests/baselines/reference/tsxElementResolution4.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/jsx/file.tsx(16,7): error TS2322: Type '{ q: ""; }' is not assignable to type '{ m: string; }'. - Property 'q' does not exist on type '{ m: string; }'. + Property 'm' is missing in type '{ q: ""; }'. ==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== @@ -21,5 +21,5 @@ tests/cases/conformance/jsx/file.tsx(16,7): error TS2322: Type '{ q: ""; }' is n ; ~~~~ !!! error TS2322: Type '{ q: ""; }' is not assignable to type '{ m: string; }'. -!!! error TS2322: Property 'q' does not exist on type '{ m: string; }'. +!!! error TS2322: Property 'm' is missing in type '{ q: ""; }'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxGenericAttributesType1.js b/tests/baselines/reference/tsxGenericAttributesType1.js new file mode 100644 index 00000000000..5d3d388396a --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType1.js @@ -0,0 +1,28 @@ +//// [file.tsx] +import React = require('react'); + +const decorator = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; + +const decorator2 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; + +const decorator3 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +var decorator = function (Component) { + return function (props) { return ; }; +}; +var decorator2 = function (Component) { + return function (props) { return ; }; +}; +var decorator3 = function (Component) { + return function (props) { return ; }; +}; diff --git a/tests/baselines/reference/tsxGenericAttributesType1.symbols b/tests/baselines/reference/tsxGenericAttributesType1.symbols new file mode 100644 index 00000000000..473de9b5c72 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType1.symbols @@ -0,0 +1,66 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +const decorator = function (Component: React.StatelessComponent): React.StatelessComponent { +>decorator : Symbol(decorator, Decl(file.tsx, 2, 5)) +>T : Symbol(T, Decl(file.tsx, 2, 28)) +>Component : Symbol(Component, Decl(file.tsx, 2, 31)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>StatelessComponent : Symbol(React.StatelessComponent, Decl(react.d.ts, 197, 40)) +>T : Symbol(T, Decl(file.tsx, 2, 28)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>StatelessComponent : Symbol(React.StatelessComponent, Decl(react.d.ts, 197, 40)) +>T : Symbol(T, Decl(file.tsx, 2, 28)) + + return (props) => +>props : Symbol(props, Decl(file.tsx, 3, 12)) +>Component : Symbol(Component, Decl(file.tsx, 2, 31)) +>props : Symbol(props, Decl(file.tsx, 3, 12)) +>Component : Symbol(Component, Decl(file.tsx, 2, 31)) + +}; + +const decorator2 = function (Component: React.StatelessComponent): React.StatelessComponent { +>decorator2 : Symbol(decorator2, Decl(file.tsx, 6, 5)) +>T : Symbol(T, Decl(file.tsx, 6, 29)) +>x : Symbol(x, Decl(file.tsx, 6, 40)) +>Component : Symbol(Component, Decl(file.tsx, 6, 54)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>StatelessComponent : Symbol(React.StatelessComponent, Decl(react.d.ts, 197, 40)) +>T : Symbol(T, Decl(file.tsx, 6, 29)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>StatelessComponent : Symbol(React.StatelessComponent, Decl(react.d.ts, 197, 40)) +>T : Symbol(T, Decl(file.tsx, 6, 29)) + + return (props) => +>props : Symbol(props, Decl(file.tsx, 7, 12)) +>Component : Symbol(Component, Decl(file.tsx, 6, 54)) +>props : Symbol(props, Decl(file.tsx, 7, 12)) +>x : Symbol(x, Decl(file.tsx, 7, 43)) +>Component : Symbol(Component, Decl(file.tsx, 6, 54)) + +}; + +const decorator3 = function (Component: React.StatelessComponent): React.StatelessComponent { +>decorator3 : Symbol(decorator3, Decl(file.tsx, 10, 5)) +>T : Symbol(T, Decl(file.tsx, 10, 29)) +>x : Symbol(x, Decl(file.tsx, 10, 40)) +>U : Symbol(U, Decl(file.tsx, 10, 53)) +>x : Symbol(x, Decl(file.tsx, 10, 65)) +>Component : Symbol(Component, Decl(file.tsx, 10, 80)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>StatelessComponent : Symbol(React.StatelessComponent, Decl(react.d.ts, 197, 40)) +>T : Symbol(T, Decl(file.tsx, 10, 29)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>StatelessComponent : Symbol(React.StatelessComponent, Decl(react.d.ts, 197, 40)) +>T : Symbol(T, Decl(file.tsx, 10, 29)) + + return (props) => +>props : Symbol(props, Decl(file.tsx, 11, 12)) +>Component : Symbol(Component, Decl(file.tsx, 10, 80)) +>x : Symbol(x, Decl(file.tsx, 11, 32)) +>props : Symbol(props, Decl(file.tsx, 11, 12)) +>Component : Symbol(Component, Decl(file.tsx, 10, 80)) + +}; diff --git a/tests/baselines/reference/tsxGenericAttributesType1.types b/tests/baselines/reference/tsxGenericAttributesType1.types new file mode 100644 index 00000000000..50be358302e --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType1.types @@ -0,0 +1,77 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +const decorator = function (Component: React.StatelessComponent): React.StatelessComponent { +>decorator : (Component: React.StatelessComponent) => React.StatelessComponent +>function (Component: React.StatelessComponent): React.StatelessComponent { return (props) => } : (Component: React.StatelessComponent) => React.StatelessComponent +>T : T +>Component : React.StatelessComponent +>React : any +>StatelessComponent : React.StatelessComponent

+>T : T +>React : any +>StatelessComponent : React.StatelessComponent

+>T : T + + return (props) => +>(props) => : (props: T & { children?: React.ReactNode; }) => JSX.Element +>props : T & { children?: React.ReactNode; } +> : JSX.Element +>Component : React.StatelessComponent +>props : T & { children?: React.ReactNode; } +>Component : React.StatelessComponent + +}; + +const decorator2 = function (Component: React.StatelessComponent): React.StatelessComponent { +>decorator2 : (Component: React.StatelessComponent) => React.StatelessComponent +>function (Component: React.StatelessComponent): React.StatelessComponent { return (props) => } : (Component: React.StatelessComponent) => React.StatelessComponent +>T : T +>x : number +>Component : React.StatelessComponent +>React : any +>StatelessComponent : React.StatelessComponent

+>T : T +>React : any +>StatelessComponent : React.StatelessComponent

+>T : T + + return (props) => +>(props) => : (props: T & { children?: React.ReactNode; }) => JSX.Element +>props : T & { children?: React.ReactNode; } +> : JSX.Element +>Component : React.StatelessComponent +>props : T & { children?: React.ReactNode; } +>x : number +>2 : 2 +>Component : React.StatelessComponent + +}; + +const decorator3 = function (Component: React.StatelessComponent): React.StatelessComponent { +>decorator3 : (Component: React.StatelessComponent) => React.StatelessComponent +>function (Component: React.StatelessComponent): React.StatelessComponent { return (props) => } : (Component: React.StatelessComponent) => React.StatelessComponent +>T : T +>x : number +>U : U +>x : number +>Component : React.StatelessComponent +>React : any +>StatelessComponent : React.StatelessComponent

+>T : T +>React : any +>StatelessComponent : React.StatelessComponent

+>T : T + + return (props) => +>(props) => : (props: T & { children?: React.ReactNode; }) => JSX.Element +>props : T & { children?: React.ReactNode; } +> : JSX.Element +>Component : React.StatelessComponent +>x : number +>2 : 2 +>props : T & { children?: React.ReactNode; } +>Component : React.StatelessComponent + +}; diff --git a/tests/baselines/reference/tsxGenericAttributesType2.errors.txt b/tests/baselines/reference/tsxGenericAttributesType2.errors.txt new file mode 100644 index 00000000000..cbd926c9b69 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType2.errors.txt @@ -0,0 +1,11 @@ +tests/cases/conformance/jsx/file.tsx(4,45): error TS2339: Property 'y' does not exist on type 'IntrinsicAttributes & { x: number; } & { children?: ReactNode; }'. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + import React = require('react'); + + const decorator4 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => + ~~~~~~~~~~ +!!! error TS2339: Property 'y' does not exist on type 'IntrinsicAttributes & { x: number; } & { children?: ReactNode; }'. + }; \ No newline at end of file diff --git a/tests/baselines/reference/tsxGenericAttributesType2.js b/tests/baselines/reference/tsxGenericAttributesType2.js new file mode 100644 index 00000000000..7b46d08c2c4 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType2.js @@ -0,0 +1,14 @@ +//// [file.tsx] +import React = require('react'); + +const decorator4 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +var decorator4 = function (Component) { + return function (props) { return ; }; +}; diff --git a/tests/baselines/reference/tsxGenericAttributesType3.js b/tests/baselines/reference/tsxGenericAttributesType3.js new file mode 100644 index 00000000000..51491d99aa2 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType3.js @@ -0,0 +1,48 @@ +//// [file.tsx] +import React = require('react'); + +class B1 extends React.Component { + render() { + return

hi
; + } +} +class B extends React.Component { + render() { + return ; + } +} + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var B1 = (function (_super) { + __extends(B1, _super); + function B1() { + return _super !== null && _super.apply(this, arguments) || this; + } + B1.prototype.render = function () { + return
hi
; + }; + return B1; +}(React.Component)); +var B = (function (_super) { + __extends(B, _super); + function B() { + return _super !== null && _super.apply(this, arguments) || this; + } + B.prototype.render = function () { + return ; + }; + return B; +}(React.Component)); diff --git a/tests/baselines/reference/tsxGenericAttributesType3.symbols b/tests/baselines/reference/tsxGenericAttributesType3.symbols new file mode 100644 index 00000000000..8c235257e8d --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType3.symbols @@ -0,0 +1,41 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +class B1 extends React.Component { +>B1 : Symbol(B1, Decl(file.tsx, 0, 32)) +>T : Symbol(T, Decl(file.tsx, 2, 9)) +>x : Symbol(x, Decl(file.tsx, 2, 20)) +>x : Symbol(x, Decl(file.tsx, 2, 36)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>T : Symbol(T, Decl(file.tsx, 2, 9)) + + render() { +>render : Symbol(B1.render, Decl(file.tsx, 2, 82)) + + return
hi
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + } +} +class B extends React.Component { +>B : Symbol(B, Decl(file.tsx, 6, 1)) +>U : Symbol(U, Decl(file.tsx, 7, 8)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>U : Symbol(U, Decl(file.tsx, 7, 8)) + + render() { +>render : Symbol(B.render, Decl(file.tsx, 7, 43)) + + return ; +>B1 : Symbol(B1, Decl(file.tsx, 0, 32)) +>this.props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) +>this : Symbol(B, Decl(file.tsx, 6, 1)) +>props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) +>x : Symbol(x, Decl(file.tsx, 9, 34)) + } +} diff --git a/tests/baselines/reference/tsxGenericAttributesType3.types b/tests/baselines/reference/tsxGenericAttributesType3.types new file mode 100644 index 00000000000..72674ac5bf7 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType3.types @@ -0,0 +1,43 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +class B1 extends React.Component { +>B1 : B1 +>T : T +>x : string +>x : string +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>T : T + + render() { +>render : () => JSX.Element + + return
hi
; +>
hi
: JSX.Element +>div : any +>div : any + } +} +class B extends React.Component { +>B : B +>U : U +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>U : U + + render() { +>render : () => JSX.Element + + return ; +> : JSX.Element +>B1 : typeof B1 +>this.props : U & { children?: React.ReactNode; } +>this : this +>props : U & { children?: React.ReactNode; } +>x : string + } +} diff --git a/tests/baselines/reference/tsxGenericAttributesType4.errors.txt b/tests/baselines/reference/tsxGenericAttributesType4.errors.txt new file mode 100644 index 00000000000..ee91f938b9f --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType4.errors.txt @@ -0,0 +1,19 @@ +tests/cases/conformance/jsx/file.tsx(11,36): error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + import React = require('react'); + + class B1 extends React.Component { + render() { + return
hi
; + } + } + class B extends React.Component { + render() { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + ~~~~~~ +!!! error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/tsxGenericAttributesType4.js b/tests/baselines/reference/tsxGenericAttributesType4.js new file mode 100644 index 00000000000..a00d03cd61b --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType4.js @@ -0,0 +1,50 @@ +//// [file.tsx] +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + render() { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + } +} + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var B1 = (function (_super) { + __extends(B1, _super); + function B1() { + return _super !== null && _super.apply(this, arguments) || this; + } + B1.prototype.render = function () { + return
hi
; + }; + return B1; +}(React.Component)); +var B = (function (_super) { + __extends(B, _super); + function B() { + return _super !== null && _super.apply(this, arguments) || this; + } + B.prototype.render = function () { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + }; + return B; +}(React.Component)); diff --git a/tests/baselines/reference/tsxGenericAttributesType5.errors.txt b/tests/baselines/reference/tsxGenericAttributesType5.errors.txt new file mode 100644 index 00000000000..83f07326f92 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType5.errors.txt @@ -0,0 +1,20 @@ +tests/cases/conformance/jsx/file.tsx(12,36): error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + import React = require('react'); + + class B1 extends React.Component { + render() { + return
hi
; + } + } + class B extends React.Component { + props: U; + render() { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + ~~~~~~ +!!! error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/tsxGenericAttributesType5.js b/tests/baselines/reference/tsxGenericAttributesType5.js new file mode 100644 index 00000000000..cb535417dd6 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType5.js @@ -0,0 +1,51 @@ +//// [file.tsx] +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + props: U; + render() { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + } +} + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var B1 = (function (_super) { + __extends(B1, _super); + function B1() { + return _super !== null && _super.apply(this, arguments) || this; + } + B1.prototype.render = function () { + return
hi
; + }; + return B1; +}(React.Component)); +var B = (function (_super) { + __extends(B, _super); + function B() { + return _super !== null && _super.apply(this, arguments) || this; + } + B.prototype.render = function () { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + }; + return B; +}(React.Component)); diff --git a/tests/baselines/reference/tsxGenericAttributesType6.js b/tests/baselines/reference/tsxGenericAttributesType6.js new file mode 100644 index 00000000000..84cab3e1f94 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType6.js @@ -0,0 +1,49 @@ +//// [file.tsx] +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + props: U; + render() { + return ; + } +} + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var B1 = (function (_super) { + __extends(B1, _super); + function B1() { + return _super !== null && _super.apply(this, arguments) || this; + } + B1.prototype.render = function () { + return
hi
; + }; + return B1; +}(React.Component)); +var B = (function (_super) { + __extends(B, _super); + function B() { + return _super !== null && _super.apply(this, arguments) || this; + } + B.prototype.render = function () { + return ; + }; + return B; +}(React.Component)); diff --git a/tests/baselines/reference/tsxGenericAttributesType6.symbols b/tests/baselines/reference/tsxGenericAttributesType6.symbols new file mode 100644 index 00000000000..27c8ed2d6dc --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType6.symbols @@ -0,0 +1,45 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +class B1 extends React.Component { +>B1 : Symbol(B1, Decl(file.tsx, 0, 32)) +>T : Symbol(T, Decl(file.tsx, 2, 9)) +>x : Symbol(x, Decl(file.tsx, 2, 20)) +>x : Symbol(x, Decl(file.tsx, 2, 36)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>T : Symbol(T, Decl(file.tsx, 2, 9)) + + render() { +>render : Symbol(B1.render, Decl(file.tsx, 2, 82)) + + return
hi
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + } +} +class B extends React.Component { +>B : Symbol(B, Decl(file.tsx, 6, 1)) +>U : Symbol(U, Decl(file.tsx, 7, 8)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>U : Symbol(U, Decl(file.tsx, 7, 8)) + + props: U; +>props : Symbol(B.props, Decl(file.tsx, 7, 43)) +>U : Symbol(U, Decl(file.tsx, 7, 8)) + + render() { +>render : Symbol(B.render, Decl(file.tsx, 8, 13)) + + return ; +>B1 : Symbol(B1, Decl(file.tsx, 0, 32)) +>this.props : Symbol(B.props, Decl(file.tsx, 7, 43)) +>this : Symbol(B, Decl(file.tsx, 6, 1)) +>props : Symbol(B.props, Decl(file.tsx, 7, 43)) +>x : Symbol(x, Decl(file.tsx, 10, 34)) + } +} diff --git a/tests/baselines/reference/tsxGenericAttributesType6.types b/tests/baselines/reference/tsxGenericAttributesType6.types new file mode 100644 index 00000000000..662b6299dad --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType6.types @@ -0,0 +1,47 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +class B1 extends React.Component { +>B1 : B1 +>T : T +>x : string +>x : string +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>T : T + + render() { +>render : () => JSX.Element + + return
hi
; +>
hi
: JSX.Element +>div : any +>div : any + } +} +class B extends React.Component { +>B : B +>U : U +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>U : U + + props: U; +>props : U +>U : U + + render() { +>render : () => JSX.Element + + return ; +> : JSX.Element +>B1 : typeof B1 +>this.props : U +>this : this +>props : U +>x : string + } +} diff --git a/tests/baselines/reference/tsxGenericAttributesType7.js b/tests/baselines/reference/tsxGenericAttributesType7.js new file mode 100644 index 00000000000..4e254f25e55 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType7.js @@ -0,0 +1,22 @@ +//// [file.tsx] +import React = require('react'); + +declare function Component(props: T) : JSX.Element; +const decorator = function (props: U) { + return ; +} + +const decorator1 = function (props: U) { + return ; +} + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +var decorator = function (props) { + return ; +}; +var decorator1 = function (props) { + return ; +}; diff --git a/tests/baselines/reference/tsxGenericAttributesType7.symbols b/tests/baselines/reference/tsxGenericAttributesType7.symbols new file mode 100644 index 00000000000..e31042bd843 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType7.symbols @@ -0,0 +1,35 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +declare function Component(props: T) : JSX.Element; +>Component : Symbol(Component, Decl(file.tsx, 0, 32)) +>T : Symbol(T, Decl(file.tsx, 2, 27)) +>props : Symbol(props, Decl(file.tsx, 2, 30)) +>T : Symbol(T, Decl(file.tsx, 2, 27)) +>JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) +>Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) + +const decorator = function (props: U) { +>decorator : Symbol(decorator, Decl(file.tsx, 3, 5)) +>U : Symbol(U, Decl(file.tsx, 3, 28)) +>props : Symbol(props, Decl(file.tsx, 3, 31)) +>U : Symbol(U, Decl(file.tsx, 3, 28)) + + return ; +>Component : Symbol(Component, Decl(file.tsx, 0, 32)) +>props : Symbol(props, Decl(file.tsx, 3, 31)) +} + +const decorator1 = function (props: U) { +>decorator1 : Symbol(decorator1, Decl(file.tsx, 7, 5)) +>U : Symbol(U, Decl(file.tsx, 7, 29)) +>x : Symbol(x, Decl(file.tsx, 7, 40)) +>props : Symbol(props, Decl(file.tsx, 7, 52)) +>U : Symbol(U, Decl(file.tsx, 7, 29)) + + return ; +>Component : Symbol(Component, Decl(file.tsx, 0, 32)) +>props : Symbol(props, Decl(file.tsx, 7, 52)) +>x : Symbol(x, Decl(file.tsx, 8, 32)) +} diff --git a/tests/baselines/reference/tsxGenericAttributesType7.types b/tests/baselines/reference/tsxGenericAttributesType7.types new file mode 100644 index 00000000000..58d853e4881 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType7.types @@ -0,0 +1,39 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +declare function Component(props: T) : JSX.Element; +>Component : (props: T) => JSX.Element +>T : T +>props : T +>T : T +>JSX : any +>Element : JSX.Element + +const decorator = function (props: U) { +>decorator : (props: U) => JSX.Element +>function (props: U) { return ;} : (props: U) => JSX.Element +>U : U +>props : U +>U : U + + return ; +> : JSX.Element +>Component : (props: T) => JSX.Element +>props : U +} + +const decorator1 = function (props: U) { +>decorator1 : (props: U) => JSX.Element +>function (props: U) { return ;} : (props: U) => JSX.Element +>U : U +>x : string +>props : U +>U : U + + return ; +> : JSX.Element +>Component : (props: T) => JSX.Element +>props : U +>x : string +} diff --git a/tests/baselines/reference/tsxGenericAttributesType8.js b/tests/baselines/reference/tsxGenericAttributesType8.js new file mode 100644 index 00000000000..435bf425c6a --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType8.js @@ -0,0 +1,22 @@ +//// [file.tsx] +import React = require('react'); + +declare function Component(props: T) : JSX.Element; +const decorator = function (props: U) { + return ; +} + +const decorator1 = function (props: U) { + return ; +} + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +var decorator = function (props) { + return ; +}; +var decorator1 = function (props) { + return ; +}; diff --git a/tests/baselines/reference/tsxGenericAttributesType8.symbols b/tests/baselines/reference/tsxGenericAttributesType8.symbols new file mode 100644 index 00000000000..516dbe9c322 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType8.symbols @@ -0,0 +1,34 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +declare function Component(props: T) : JSX.Element; +>Component : Symbol(Component, Decl(file.tsx, 0, 32)) +>T : Symbol(T, Decl(file.tsx, 2, 27)) +>props : Symbol(props, Decl(file.tsx, 2, 30)) +>T : Symbol(T, Decl(file.tsx, 2, 27)) +>JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) +>Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) + +const decorator = function (props: U) { +>decorator : Symbol(decorator, Decl(file.tsx, 3, 5)) +>U : Symbol(U, Decl(file.tsx, 3, 28)) +>props : Symbol(props, Decl(file.tsx, 3, 31)) +>U : Symbol(U, Decl(file.tsx, 3, 28)) + + return ; +>Component : Symbol(Component, Decl(file.tsx, 0, 32)) +>props : Symbol(props, Decl(file.tsx, 3, 31)) +} + +const decorator1 = function (props: U) { +>decorator1 : Symbol(decorator1, Decl(file.tsx, 7, 5)) +>U : Symbol(U, Decl(file.tsx, 7, 29)) +>x : Symbol(x, Decl(file.tsx, 7, 40)) +>props : Symbol(props, Decl(file.tsx, 7, 52)) +>U : Symbol(U, Decl(file.tsx, 7, 29)) + + return ; +>Component : Symbol(Component, Decl(file.tsx, 0, 32)) +>props : Symbol(props, Decl(file.tsx, 7, 52)) +} diff --git a/tests/baselines/reference/tsxGenericAttributesType8.types b/tests/baselines/reference/tsxGenericAttributesType8.types new file mode 100644 index 00000000000..b2a62a575ff --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType8.types @@ -0,0 +1,38 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +declare function Component(props: T) : JSX.Element; +>Component : (props: T) => JSX.Element +>T : T +>props : T +>T : T +>JSX : any +>Element : JSX.Element + +const decorator = function (props: U) { +>decorator : (props: U) => JSX.Element +>function (props: U) { return ;} : (props: U) => JSX.Element +>U : U +>props : U +>U : U + + return ; +> : JSX.Element +>Component : (props: T) => JSX.Element +>props : U +} + +const decorator1 = function (props: U) { +>decorator1 : (props: U) => JSX.Element +>function (props: U) { return ;} : (props: U) => JSX.Element +>U : U +>x : string +>props : U +>U : U + + return ; +> : JSX.Element +>Component : (props: T) => JSX.Element +>props : U +} diff --git a/tests/baselines/reference/tsxGenericAttributesType9.js b/tests/baselines/reference/tsxGenericAttributesType9.js new file mode 100644 index 00000000000..b7b90736ad1 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType9.js @@ -0,0 +1,40 @@ +//// [file.tsx] +import React = require('react'); + +export function makeP

(Ctor: React.ComponentClass

): React.ComponentClass

{ + return class extends React.PureComponent { + public render(): JSX.Element { + return ( + + ); + } + }; +} + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +function makeP(Ctor) { + return (function (_super) { + __extends(class_1, _super); + function class_1() { + return _super !== null && _super.apply(this, arguments) || this; + } + class_1.prototype.render = function () { + return (); + }; + return class_1; + }(React.PureComponent)); +} +exports.makeP = makeP; diff --git a/tests/baselines/reference/tsxGenericAttributesType9.symbols b/tests/baselines/reference/tsxGenericAttributesType9.symbols new file mode 100644 index 00000000000..f4df2e79408 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType9.symbols @@ -0,0 +1,37 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +export function makeP

(Ctor: React.ComponentClass

): React.ComponentClass

{ +>makeP : Symbol(makeP, Decl(file.tsx, 0, 32)) +>P : Symbol(P, Decl(file.tsx, 2, 22)) +>Ctor : Symbol(Ctor, Decl(file.tsx, 2, 25)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>ComponentClass : Symbol(React.ComponentClass, Decl(react.d.ts, 204, 5)) +>P : Symbol(P, Decl(file.tsx, 2, 22)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>ComponentClass : Symbol(React.ComponentClass, Decl(react.d.ts, 204, 5)) +>P : Symbol(P, Decl(file.tsx, 2, 22)) + + return class extends React.PureComponent { +>React.PureComponent : Symbol(React.PureComponent, Decl(react.d.ts, 179, 5)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>PureComponent : Symbol(React.PureComponent, Decl(react.d.ts, 179, 5)) +>P : Symbol(P, Decl(file.tsx, 2, 22)) + + public render(): JSX.Element { +>render : Symbol((Anonymous class).render, Decl(file.tsx, 3, 52)) +>JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) +>Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) + + return ( + +>Ctor : Symbol(Ctor, Decl(file.tsx, 2, 25)) +>this.props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) +>this : Symbol((Anonymous class), Decl(file.tsx, 3, 7)) +>props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) + + ); + } + }; +} diff --git a/tests/baselines/reference/tsxGenericAttributesType9.types b/tests/baselines/reference/tsxGenericAttributesType9.types new file mode 100644 index 00000000000..a1d7efc49be --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType9.types @@ -0,0 +1,41 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +export function makeP

(Ctor: React.ComponentClass

): React.ComponentClass

{ +>makeP :

(Ctor: React.ComponentClass

) => React.ComponentClass

+>P : P +>Ctor : React.ComponentClass

+>React : any +>ComponentClass : React.ComponentClass

+>P : P +>React : any +>ComponentClass : React.ComponentClass

+>P : P + + return class extends React.PureComponent { +>class extends React.PureComponent { public render(): JSX.Element { return ( ); } } : typeof (Anonymous class) +>React.PureComponent : React.PureComponent +>React : typeof React +>PureComponent : typeof React.PureComponent +>P : P + + public render(): JSX.Element { +>render : () => JSX.Element +>JSX : any +>Element : JSX.Element + + return ( +>( ) : JSX.Element + + +> : JSX.Element +>Ctor : React.ComponentClass

+>this.props : P & { children?: React.ReactNode; } +>this : this +>props : P & { children?: React.ReactNode; } + + ); + } + }; +} diff --git a/tests/baselines/reference/tsxReactComponentWithDefaultTypeParameter3.errors.txt b/tests/baselines/reference/tsxReactComponentWithDefaultTypeParameter3.errors.txt index c49bd643537..230ca1e2795 100644 --- a/tests/baselines/reference/tsxReactComponentWithDefaultTypeParameter3.errors.txt +++ b/tests/baselines/reference/tsxReactComponentWithDefaultTypeParameter3.errors.txt @@ -1,7 +1,5 @@ -tests/cases/conformance/jsx/file.tsx(16,17): error TS2322: Type '{ a: 10; b: "hi"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. - Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. -tests/cases/conformance/jsx/file.tsx(17,18): error TS2322: Type '{ a: "hi"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. - Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. +tests/cases/conformance/jsx/file.tsx(16,17): error TS2339: Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. +tests/cases/conformance/jsx/file.tsx(17,18): error TS2339: Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. ==== tests/cases/conformance/jsx/file.tsx (2 errors) ==== @@ -21,10 +19,8 @@ tests/cases/conformance/jsx/file.tsx(17,18): error TS2322: Type '{ a: "hi"; }' i // Error let x = - ~~~~~~~~~~~~~ -!!! error TS2322: Type '{ a: 10; b: "hi"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. -!!! error TS2322: Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. + ~~~~~~ +!!! error TS2339: Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. let x2 = ~~~~~~ -!!! error TS2322: Type '{ a: "hi"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. -!!! error TS2322: Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. \ No newline at end of file +!!! error TS2339: Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution12.errors.txt b/tests/baselines/reference/tsxSpreadAttributesResolution12.errors.txt index 0c1ebce61bf..a43c9270642 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution12.errors.txt +++ b/tests/baselines/reference/tsxSpreadAttributesResolution12.errors.txt @@ -6,9 +6,13 @@ tests/cases/conformance/jsx/file.tsx(28,25): error TS2322: Type '{ y: true; x: 3 Type '{ y: true; x: 3; overwrite: "hi"; }' is not assignable to type 'Prop'. Types of property 'x' are incompatible. Type '3' is not assignable to type '2'. +tests/cases/conformance/jsx/file.tsx(30,25): error TS2322: Type '{ y: true; x: 2; overwrite: "hi"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Prop & { children?: ReactNode; }'. + Type '{ y: true; x: 2; overwrite: "hi"; }' is not assignable to type 'Prop'. + Types of property 'y' are incompatible. + Type 'true' is not assignable to type 'false'. -==== tests/cases/conformance/jsx/file.tsx (2 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== import React = require('react'); const obj = {}; @@ -48,4 +52,11 @@ tests/cases/conformance/jsx/file.tsx(28,25): error TS2322: Type '{ y: true; x: 3 !!! error TS2322: Types of property 'x' are incompatible. !!! error TS2322: Type '3' is not assignable to type '2'. let x2 = + let x3 = + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ y: true; x: 2; overwrite: "hi"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Prop & { children?: ReactNode; }'. +!!! error TS2322: Type '{ y: true; x: 2; overwrite: "hi"; }' is not assignable to type 'Prop'. +!!! error TS2322: Types of property 'y' are incompatible. +!!! error TS2322: Type 'true' is not assignable to type 'false'. + \ No newline at end of file diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution12.js b/tests/baselines/reference/tsxSpreadAttributesResolution12.js index 8551a3f1bac..a68755a7592 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution12.js +++ b/tests/baselines/reference/tsxSpreadAttributesResolution12.js @@ -28,6 +28,8 @@ let anyobj: any; let x = let x1 = let x2 = +let x3 = + //// [file.jsx] @@ -67,3 +69,4 @@ var anyobj; var x = ; var x1 = ; var x2 = ; +var x3 = ; diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution13.js b/tests/baselines/reference/tsxSpreadAttributesResolution13.js new file mode 100644 index 00000000000..8227f3d6399 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution13.js @@ -0,0 +1,48 @@ +//// [file.tsx] +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + let condition1: boolean; + if (condition1) { + return ( + + ); + } + else { + return (); + } +} + +interface AnotherComponentProps { + property1: string; +} + +function ChildComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +function Component(props) { + var condition1; + if (condition1) { + return (); + } + else { + return (); + } +} +exports["default"] = Component; +function ChildComponent(_a) { + var property1 = _a.property1; + return ({property1}); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution13.symbols b/tests/baselines/reference/tsxSpreadAttributesResolution13.symbols new file mode 100644 index 00000000000..2e146225792 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution13.symbols @@ -0,0 +1,60 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +interface ComponentProps { +>ComponentProps : Symbol(ComponentProps, Decl(file.tsx, 0, 32)) + + property1: string; +>property1 : Symbol(ComponentProps.property1, Decl(file.tsx, 2, 26)) + + property2: number; +>property2 : Symbol(ComponentProps.property2, Decl(file.tsx, 3, 22)) +} + +export default function Component(props: ComponentProps) { +>Component : Symbol(Component, Decl(file.tsx, 5, 1)) +>props : Symbol(props, Decl(file.tsx, 7, 34)) +>ComponentProps : Symbol(ComponentProps, Decl(file.tsx, 0, 32)) + + let condition1: boolean; +>condition1 : Symbol(condition1, Decl(file.tsx, 8, 7)) + + if (condition1) { +>condition1 : Symbol(condition1, Decl(file.tsx, 8, 7)) + + return ( + +>ChildComponent : Symbol(ChildComponent, Decl(file.tsx, 21, 1)) +>props : Symbol(props, Decl(file.tsx, 7, 34)) + + ); + } + else { + return (); +>ChildComponent : Symbol(ChildComponent, Decl(file.tsx, 21, 1)) +>props : Symbol(props, Decl(file.tsx, 7, 34)) +>property1 : Symbol(property1, Decl(file.tsx, 15, 42)) + } +} + +interface AnotherComponentProps { +>AnotherComponentProps : Symbol(AnotherComponentProps, Decl(file.tsx, 17, 1)) + + property1: string; +>property1 : Symbol(AnotherComponentProps.property1, Decl(file.tsx, 19, 33)) +} + +function ChildComponent({ property1 }: AnotherComponentProps) { +>ChildComponent : Symbol(ChildComponent, Decl(file.tsx, 21, 1)) +>property1 : Symbol(property1, Decl(file.tsx, 23, 25)) +>AnotherComponentProps : Symbol(AnotherComponentProps, Decl(file.tsx, 17, 1)) + + return ( + {property1} +>span : Symbol(JSX.IntrinsicElements.span, Decl(react.d.ts, 2460, 51)) +>property1 : Symbol(property1, Decl(file.tsx, 23, 25)) +>span : Symbol(JSX.IntrinsicElements.span, Decl(react.d.ts, 2460, 51)) + + ); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution13.types b/tests/baselines/reference/tsxSpreadAttributesResolution13.types new file mode 100644 index 00000000000..0ad324c25b1 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution13.types @@ -0,0 +1,68 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +interface ComponentProps { +>ComponentProps : ComponentProps + + property1: string; +>property1 : string + + property2: number; +>property2 : number +} + +export default function Component(props: ComponentProps) { +>Component : (props: ComponentProps) => JSX.Element +>props : ComponentProps +>ComponentProps : ComponentProps + + let condition1: boolean; +>condition1 : boolean + + if (condition1) { +>condition1 : boolean + + return ( +>( ) : JSX.Element + + +> : JSX.Element +>ChildComponent : ({ property1 }: AnotherComponentProps) => JSX.Element +>props : ComponentProps + + ); + } + else { + return (); +>() : JSX.Element +> : JSX.Element +>ChildComponent : ({ property1 }: AnotherComponentProps) => JSX.Element +>props : ComponentProps +>property1 : string + } +} + +interface AnotherComponentProps { +>AnotherComponentProps : AnotherComponentProps + + property1: string; +>property1 : string +} + +function ChildComponent({ property1 }: AnotherComponentProps) { +>ChildComponent : ({ property1 }: AnotherComponentProps) => JSX.Element +>property1 : string +>AnotherComponentProps : AnotherComponentProps + + return ( +>( {property1} ) : JSX.Element + + {property1} +>{property1} : JSX.Element +>span : any +>property1 : string +>span : any + + ); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution14.errors.txt b/tests/baselines/reference/tsxSpreadAttributesResolution14.errors.txt new file mode 100644 index 00000000000..536d2e75f84 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution14.errors.txt @@ -0,0 +1,29 @@ +tests/cases/conformance/jsx/file.tsx(11,38): error TS2339: Property 'Property1' does not exist on type 'IntrinsicAttributes & AnotherComponentProps'. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + import React = require('react'); + + interface ComponentProps { + property1: string; + property2: number; + } + + export default function Component(props: ComponentProps) { + return ( + // Error extra property + + ~~~~~~~~~ +!!! error TS2339: Property 'Property1' does not exist on type 'IntrinsicAttributes & AnotherComponentProps'. + ); + } + + interface AnotherComponentProps { + property1: string; + } + + function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); + } \ No newline at end of file diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution14.js b/tests/baselines/reference/tsxSpreadAttributesResolution14.js new file mode 100644 index 00000000000..d04c9cd6d99 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution14.js @@ -0,0 +1,39 @@ +//// [file.tsx] +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + // Error extra property + + ); +} + +interface AnotherComponentProps { + property1: string; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +function Component(props) { + return ( + // Error extra property + ); +} +exports["default"] = Component; +function AnotherComponent(_a) { + var property1 = _a.property1; + return ({property1}); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution15.js b/tests/baselines/reference/tsxSpreadAttributesResolution15.js new file mode 100644 index 00000000000..41302f22a61 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution15.js @@ -0,0 +1,38 @@ +//// [file.tsx] +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + + ); +} + +interface AnotherComponentProps { + property1: string; + AnotherProperty1: string; + property2: boolean; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +function Component(props) { + return (); +} +exports["default"] = Component; +function AnotherComponent(_a) { + var property1 = _a.property1; + return ({property1}); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution15.symbols b/tests/baselines/reference/tsxSpreadAttributesResolution15.symbols new file mode 100644 index 00000000000..00e10954821 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution15.symbols @@ -0,0 +1,55 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +interface ComponentProps { +>ComponentProps : Symbol(ComponentProps, Decl(file.tsx, 0, 32)) + + property1: string; +>property1 : Symbol(ComponentProps.property1, Decl(file.tsx, 2, 26)) + + property2: number; +>property2 : Symbol(ComponentProps.property2, Decl(file.tsx, 3, 22)) +} + +export default function Component(props: ComponentProps) { +>Component : Symbol(Component, Decl(file.tsx, 5, 1)) +>props : Symbol(props, Decl(file.tsx, 7, 34)) +>ComponentProps : Symbol(ComponentProps, Decl(file.tsx, 0, 32)) + + return ( + +>AnotherComponent : Symbol(AnotherComponent, Decl(file.tsx, 17, 1)) +>props : Symbol(props, Decl(file.tsx, 7, 34)) +>property2 : Symbol(property2, Decl(file.tsx, 9, 36)) +>AnotherProperty1 : Symbol(AnotherProperty1, Decl(file.tsx, 9, 46)) + + ); +} + +interface AnotherComponentProps { +>AnotherComponentProps : Symbol(AnotherComponentProps, Decl(file.tsx, 11, 1)) + + property1: string; +>property1 : Symbol(AnotherComponentProps.property1, Decl(file.tsx, 13, 33)) + + AnotherProperty1: string; +>AnotherProperty1 : Symbol(AnotherComponentProps.AnotherProperty1, Decl(file.tsx, 14, 22)) + + property2: boolean; +>property2 : Symbol(AnotherComponentProps.property2, Decl(file.tsx, 15, 29)) +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { +>AnotherComponent : Symbol(AnotherComponent, Decl(file.tsx, 17, 1)) +>property1 : Symbol(property1, Decl(file.tsx, 19, 27)) +>AnotherComponentProps : Symbol(AnotherComponentProps, Decl(file.tsx, 11, 1)) + + return ( + {property1} +>span : Symbol(JSX.IntrinsicElements.span, Decl(react.d.ts, 2460, 51)) +>property1 : Symbol(property1, Decl(file.tsx, 19, 27)) +>span : Symbol(JSX.IntrinsicElements.span, Decl(react.d.ts, 2460, 51)) + + ); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution15.types b/tests/baselines/reference/tsxSpreadAttributesResolution15.types new file mode 100644 index 00000000000..152ad3f696e --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution15.types @@ -0,0 +1,61 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +interface ComponentProps { +>ComponentProps : ComponentProps + + property1: string; +>property1 : string + + property2: number; +>property2 : number +} + +export default function Component(props: ComponentProps) { +>Component : (props: ComponentProps) => JSX.Element +>props : ComponentProps +>ComponentProps : ComponentProps + + return ( +>( ) : JSX.Element + + +> : JSX.Element +>AnotherComponent : ({ property1 }: AnotherComponentProps) => JSX.Element +>props : ComponentProps +>property2 : true +>AnotherProperty1 : string + + ); +} + +interface AnotherComponentProps { +>AnotherComponentProps : AnotherComponentProps + + property1: string; +>property1 : string + + AnotherProperty1: string; +>AnotherProperty1 : string + + property2: boolean; +>property2 : boolean +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { +>AnotherComponent : ({ property1 }: AnotherComponentProps) => JSX.Element +>property1 : string +>AnotherComponentProps : AnotherComponentProps + + return ( +>( {property1} ) : JSX.Element + + {property1} +>{property1} : JSX.Element +>span : any +>property1 : string +>span : any + + ); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution16.errors.txt b/tests/baselines/reference/tsxSpreadAttributesResolution16.errors.txt new file mode 100644 index 00000000000..ddfb9c1c6cf --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution16.errors.txt @@ -0,0 +1,35 @@ +tests/cases/conformance/jsx/file.tsx(11,27): error TS2322: Type '{ property1: string; property2: number; }' is not assignable to type 'IntrinsicAttributes & AnotherComponentProps'. + Type '{ property1: string; property2: number; }' is not assignable to type 'AnotherComponentProps'. + Property 'AnotherProperty1' is missing in type '{ property1: string; property2: number; }'. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + import React = require('react'); + + interface ComponentProps { + property1: string; + property2: number; + } + + export default function Component(props: ComponentProps) { + return ( + // Error: missing property + + ~~~~~~~~~~ +!!! error TS2322: Type '{ property1: string; property2: number; }' is not assignable to type 'IntrinsicAttributes & AnotherComponentProps'. +!!! error TS2322: Type '{ property1: string; property2: number; }' is not assignable to type 'AnotherComponentProps'. +!!! error TS2322: Property 'AnotherProperty1' is missing in type '{ property1: string; property2: number; }'. + ); + } + + interface AnotherComponentProps { + property1: string; + AnotherProperty1: string; + property2: boolean; + } + + function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); + } \ No newline at end of file diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution16.js b/tests/baselines/reference/tsxSpreadAttributesResolution16.js new file mode 100644 index 00000000000..ad0d4b01885 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution16.js @@ -0,0 +1,41 @@ +//// [file.tsx] +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + // Error: missing property + + ); +} + +interface AnotherComponentProps { + property1: string; + AnotherProperty1: string; + property2: boolean; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +function Component(props) { + return ( + // Error: missing property + ); +} +exports["default"] = Component; +function AnotherComponent(_a) { + var property1 = _a.property1; + return ({property1}); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution2.errors.txt b/tests/baselines/reference/tsxSpreadAttributesResolution2.errors.txt index 57b616124d1..06a0c4bbea6 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution2.errors.txt +++ b/tests/baselines/reference/tsxSpreadAttributesResolution2.errors.txt @@ -8,9 +8,17 @@ tests/cases/conformance/jsx/file.tsx(19,19): error TS2322: Type '{ x: true; y: t Type '{ x: true; y: true; }' is not assignable to type 'PoisonedProp'. Types of property 'x' are incompatible. Type 'true' is not assignable to type 'string'. +tests/cases/conformance/jsx/file.tsx(20,19): error TS2322: Type '{ x: number; y: "2"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. + Type '{ x: number; y: "2"; }' is not assignable to type 'PoisonedProp'. + Types of property 'x' are incompatible. + Type 'number' is not assignable to type 'string'. +tests/cases/conformance/jsx/file.tsx(21,20): error TS2322: Type '{ X: "hi"; x: number; y: "2"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. + Type '{ X: "hi"; x: number; y: "2"; }' is not assignable to type 'PoisonedProp'. + Types of property 'x' are incompatible. + Type 'number' is not assignable to type 'string'. -==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (5 errors) ==== import React = require('react'); interface PoisonedProp { @@ -42,4 +50,16 @@ tests/cases/conformance/jsx/file.tsx(19,19): error TS2322: Type '{ x: true; y: t !!! error TS2322: Type '{ x: true; y: true; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. !!! error TS2322: Type '{ x: true; y: true; }' is not assignable to type 'PoisonedProp'. !!! error TS2322: Types of property 'x' are incompatible. -!!! error TS2322: Type 'true' is not assignable to type 'string'. \ No newline at end of file +!!! error TS2322: Type 'true' is not assignable to type 'string'. + let w = ; + ~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ x: number; y: "2"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. +!!! error TS2322: Type '{ x: number; y: "2"; }' is not assignable to type 'PoisonedProp'. +!!! error TS2322: Types of property 'x' are incompatible. +!!! error TS2322: Type 'number' is not assignable to type 'string'. + let w1 = ; + ~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ X: "hi"; x: number; y: "2"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. +!!! error TS2322: Type '{ X: "hi"; x: number; y: "2"; }' is not assignable to type 'PoisonedProp'. +!!! error TS2322: Types of property 'x' are incompatible. +!!! error TS2322: Type 'number' is not assignable to type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution2.js b/tests/baselines/reference/tsxSpreadAttributesResolution2.js index 75da8fc2291..ad2af275485 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution2.js +++ b/tests/baselines/reference/tsxSpreadAttributesResolution2.js @@ -17,7 +17,9 @@ const obj = {}; // Error let p = ; let y = ; -let z = ; +let z = ; +let w = ; +let w1 = ; //// [file.jsx] "use strict"; @@ -48,3 +50,5 @@ var obj = {}; var p = ; var y = ; var z = ; +var w = ; +var w1 = ; diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution5.errors.txt b/tests/baselines/reference/tsxSpreadAttributesResolution5.errors.txt index 2212d0da025..be7018512f9 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution5.errors.txt +++ b/tests/baselines/reference/tsxSpreadAttributesResolution5.errors.txt @@ -2,11 +2,9 @@ tests/cases/conformance/jsx/file.tsx(20,19): error TS2322: Type '{ x: string; y: Type '{ x: string; y: number; }' is not assignable to type 'PoisonedProp'. Types of property 'y' are incompatible. Type 'number' is not assignable to type '2'. -tests/cases/conformance/jsx/file.tsx(33,20): error TS2322: Type '{ prop1: boolean; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. - Property 'prop1' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. -==== tests/cases/conformance/jsx/file.tsx (2 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== import React = require('react'); interface PoisonedProp { @@ -43,8 +41,5 @@ tests/cases/conformance/jsx/file.tsx(33,20): error TS2322: Type '{ prop1: boolea let o = { prop1: false } - // Error - let e = ; - ~~~~~~ -!!! error TS2322: Type '{ prop1: boolean; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. -!!! error TS2322: Property 'prop1' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. \ No newline at end of file + // Ok + let e = ; \ No newline at end of file diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution5.js b/tests/baselines/reference/tsxSpreadAttributesResolution5.js index a40139b316e..192f4b78770 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution5.js +++ b/tests/baselines/reference/tsxSpreadAttributesResolution5.js @@ -30,7 +30,7 @@ class EmptyProp extends React.Component<{}, {}> { let o = { prop1: false } -// Error +// Ok let e = ; //// [file.jsx] @@ -76,5 +76,5 @@ var EmptyProp = (function (_super) { var o = { prop1: false }; -// Error +// Ok var e = ; diff --git a/tests/baselines/reference/tsxSpreadChildren.types b/tests/baselines/reference/tsxSpreadChildren.types index 7f4609c30b8..c762e45b593 100644 --- a/tests/baselines/reference/tsxSpreadChildren.types +++ b/tests/baselines/reference/tsxSpreadChildren.types @@ -53,7 +53,7 @@ function Todo(prop: { key: number, todo: string }) { >div : any } function TodoList({ todos }: TodoListProps) { ->TodoList : ({todos}: TodoListProps) => JSX.Element +>TodoList : ({ todos }: TodoListProps) => JSX.Element >todos : TodoProp[] >TodoListProps : TodoListProps @@ -88,6 +88,6 @@ let x: TodoListProps; > : JSX.Element ->TodoList : ({todos}: TodoListProps) => JSX.Element +>TodoList : ({ todos }: TodoListProps) => JSX.Element >x : TodoListProps diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentOverload1.types b/tests/baselines/reference/tsxStatelessFunctionComponentOverload1.types index 8e288ebd34a..875f8018a95 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentOverload1.types +++ b/tests/baselines/reference/tsxStatelessFunctionComponentOverload1.types @@ -79,21 +79,21 @@ const c5 = Hello declare function TestingOneThing({y1: string}): JSX.Element; ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >y1 : any >string : any >JSX : any >Element : JSX.Element declare function TestingOneThing(j: {"extra-data": string, yy?: string}): JSX.Element; ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >j : { "extra-data": string; yy?: string; } >yy : string >JSX : any >Element : JSX.Element declare function TestingOneThing(n: {yy: number, direction?: number}): JSX.Element; ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >n : { yy: number; direction?: number; } >yy : number >direction : number @@ -101,7 +101,7 @@ declare function TestingOneThing(n: {yy: number, direction?: number}): JSX.Eleme >Element : JSX.Element declare function TestingOneThing(n: {yy: string, name: string}): JSX.Element; ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >n : { yy: string; name: string; } >yy : string >name : string @@ -112,27 +112,27 @@ declare function TestingOneThing(n: {yy: string, name: string}): JSX.Element; const d1 = ; >d1 : JSX.Element > : JSX.Element ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >y1 : true >extra-data : true const d2 = ; >d2 : JSX.Element > : JSX.Element ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >extra-data : string const d3 = ; >d3 : JSX.Element > : JSX.Element ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >extra-data : string >yy : string const d4 = ; >d4 : JSX.Element > : JSX.Element ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >extra-data : string >yy : number >9 : 9 @@ -142,7 +142,7 @@ const d4 = ; const d5 = ; >d5 : JSX.Element > : JSX.Element ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >extra-data : string >yy : string >name : string diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.errors.txt index b59b1dd44f4..4f717bfca96 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.errors.txt @@ -1,5 +1,6 @@ tests/cases/conformance/jsx/file.tsx(12,22): error TS2322: Type '{ extraProp: true; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. - Property 'extraProp' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. + Type '{ extraProp: true; }' is not assignable to type '{ yy: number; yy1: string; }'. + Property 'yy' is missing in type '{ extraProp: true; }'. tests/cases/conformance/jsx/file.tsx(13,22): error TS2322: Type '{ yy: 10; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. Type '{ yy: 10; }' is not assignable to type '{ yy: number; yy1: string; }'. Property 'yy1' is missing in type '{ yy: 10; }'. @@ -7,10 +8,7 @@ tests/cases/conformance/jsx/file.tsx(14,22): error TS2322: Type '{ yy1: true; yy Type '{ yy1: true; yy: number; }' is not assignable to type '{ yy: number; yy1: string; }'. Types of property 'yy1' are incompatible. Type 'true' is not assignable to type 'string'. -tests/cases/conformance/jsx/file.tsx(15,22): error TS2322: Type '{ extra: string; yy: number; yy1: string; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. - Property 'extra' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. -tests/cases/conformance/jsx/file.tsx(16,22): error TS2322: Type '{ y1: 10000; yy: number; yy1: string; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. - Property 'y1' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. +tests/cases/conformance/jsx/file.tsx(16,31): error TS2339: Property 'y1' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. tests/cases/conformance/jsx/file.tsx(17,22): error TS2322: Type '{ yy: boolean; yy1: string; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. Type '{ yy: boolean; yy1: string; }' is not assignable to type '{ yy: number; yy1: string; }'. Types of property 'yy' are incompatible. @@ -31,12 +29,16 @@ tests/cases/conformance/jsx/file.tsx(34,29): error TS2322: Type '{ y1: "hello"; Types of property 'y1' are incompatible. Type '"hello"' is not assignable to type 'boolean'. tests/cases/conformance/jsx/file.tsx(35,29): error TS2322: Type '{ y1: "hello"; y2: 1000; children: "hi"; }' is not assignable to type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. - Property 'children' does not exist on type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. + Type '{ y1: "hello"; y2: 1000; children: "hi"; }' is not assignable to type '{ y1: boolean; y2?: number; y3: boolean; }'. + Types of property 'y1' are incompatible. + Type '"hello"' is not assignable to type 'boolean'. tests/cases/conformance/jsx/file.tsx(36,29): error TS2322: Type '{ y1: "hello"; y2: 1000; children: string; }' is not assignable to type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. - Property 'children' does not exist on type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. + Type '{ y1: "hello"; y2: 1000; children: string; }' is not assignable to type '{ y1: boolean; y2?: number; y3: boolean; }'. + Types of property 'y1' are incompatible. + Type '"hello"' is not assignable to type 'boolean'. -==== tests/cases/conformance/jsx/file.tsx (12 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (11 errors) ==== import React = require('react') declare function OneThing(): JSX.Element; declare function OneThing(l: {yy: number, yy1: string}): JSX.Element; @@ -51,7 +53,8 @@ tests/cases/conformance/jsx/file.tsx(36,29): error TS2322: Type '{ y1: "hello"; const c0 = ; // extra property; ~~~~~~~~~ !!! error TS2322: Type '{ extraProp: true; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. -!!! error TS2322: Property 'extraProp' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. +!!! error TS2322: Type '{ extraProp: true; }' is not assignable to type '{ yy: number; yy1: string; }'. +!!! error TS2322: Property 'yy' is missing in type '{ extraProp: true; }'. const c1 = ; // missing property; ~~~~~~~ !!! error TS2322: Type '{ yy: 10; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. @@ -63,14 +66,10 @@ tests/cases/conformance/jsx/file.tsx(36,29): error TS2322: Type '{ y1: "hello"; !!! error TS2322: Type '{ yy1: true; yy: number; }' is not assignable to type '{ yy: number; yy1: string; }'. !!! error TS2322: Types of property 'yy1' are incompatible. !!! error TS2322: Type 'true' is not assignable to type 'string'. - const c3 = ; // Extra attribute; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ extra: string; yy: number; yy1: string; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. + const c3 = ; // This is OK becuase all attribute are spread const c4 = ; // extra property; - ~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ y1: 10000; yy: number; yy1: string; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. -!!! error TS2322: Property 'y1' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. + ~~~~~~~~~~ +!!! error TS2339: Property 'y1' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. const c5 = ; // type incompatible; ~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ yy: boolean; yy1: string; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. @@ -116,9 +115,13 @@ tests/cases/conformance/jsx/file.tsx(36,29): error TS2322: Type '{ y1: "hello"; const e3 = ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ y1: "hello"; y2: 1000; children: "hi"; }' is not assignable to type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. -!!! error TS2322: Property 'children' does not exist on type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. +!!! error TS2322: Type '{ y1: "hello"; y2: 1000; children: "hi"; }' is not assignable to type '{ y1: boolean; y2?: number; y3: boolean; }'. +!!! error TS2322: Types of property 'y1' are incompatible. +!!! error TS2322: Type '"hello"' is not assignable to type 'boolean'. const e4 = Hi ~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ y1: "hello"; y2: 1000; children: string; }' is not assignable to type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. -!!! error TS2322: Property 'children' does not exist on type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. +!!! error TS2322: Type '{ y1: "hello"; y2: 1000; children: string; }' is not assignable to type '{ y1: boolean; y2?: number; y3: boolean; }'. +!!! error TS2322: Types of property 'y1' are incompatible. +!!! error TS2322: Type '"hello"' is not assignable to type 'boolean'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.js b/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.js index 8da2bee37ea..d67466d1271 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.js +++ b/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.js @@ -13,7 +13,7 @@ let obj2: any; const c0 = ; // extra property; const c1 = ; // missing property; const c2 = ; // type incompatible; -const c3 = ; // Extra attribute; +const c3 = ; // This is OK becuase all attribute are spread const c4 = ; // extra property; const c5 = ; // type incompatible; const c6 = ; // Should error as there is extra attribute that doesn't match any. Current it is not @@ -50,7 +50,7 @@ define(["require", "exports", "react"], function (require, exports, React) { var c0 = ; // extra property; var c1 = ; // missing property; var c2 = ; // type incompatible; - var c3 = ; // Extra attribute; + var c3 = ; // This is OK becuase all attribute are spread var c4 = ; // extra property; var c5 = ; // type incompatible; var c6 = ; // Should error as there is extra attribute that doesn't match any. Current it is not diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt index a7b787c1c18..b7e4fc78e0e 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt @@ -1,17 +1,24 @@ tests/cases/conformance/jsx/file.tsx(48,24): error TS2322: Type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }'. tests/cases/conformance/jsx/file.tsx(49,24): error TS2322: Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ to: string; onClick: (e: any) => void; children: string; }'. tests/cases/conformance/jsx/file.tsx(50,24): error TS2322: Type '{ onClick: () => void; to: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ onClick: () => void; to: string; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ onClick: () => void; to: string; }'. tests/cases/conformance/jsx/file.tsx(51,24): error TS2322: Type '{ onClick: (k: MouseEvent) => void; to: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ onClick: (k: MouseEvent) => void; to: string; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ onClick: (k: MouseEvent) => void; to: string; }'. tests/cases/conformance/jsx/file.tsx(53,24): error TS2322: Type '{ to: string; onClick(e: any): void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ to: string; onClick(e: any): void; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ to: string; onClick(e: any): void; }'. tests/cases/conformance/jsx/file.tsx(54,24): error TS2322: Type '{ children: 10; onClick(e: any): void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ children: 10; onClick(e: any): void; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ children: 10; onClick(e: any): void; }'. tests/cases/conformance/jsx/file.tsx(55,24): error TS2322: Type '{ children: "hello"; className: true; onClick(e: any): void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ children: "hello"; className: true; onClick(e: any): void; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ children: "hello"; className: true; onClick(e: any): void; }'. tests/cases/conformance/jsx/file.tsx(56,24): error TS2322: Type '{ data-format: true; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. Type '{ data-format: true; }' is not assignable to type 'HyphenProps'. Types of property '"data-format"' are incompatible. @@ -69,32 +76,39 @@ tests/cases/conformance/jsx/file.tsx(56,24): error TS2322: Type '{ data-format: const b0 = {}}>GO; // extra property; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }'. const b1 = {}} {...obj0}>Hello world; // extra property; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ to: string; onClick: (e: any) => void; children: string; }'. const b2 = ; // extra property ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ onClick: () => void; to: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ onClick: () => void; to: string; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ onClick: () => void; to: string; }'. const b3 = {}}} />; // extra property ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ onClick: (k: MouseEvent) => void; to: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ onClick: (k: MouseEvent) => void; to: string; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ onClick: (k: MouseEvent) => void; to: string; }'. const b4 = ; // Should error because Incorrect type; but attributes are any so everything is allowed const b5 = ; // Spread retain method declaration (see GitHub #13365), so now there is an extra attributes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ to: string; onClick(e: any): void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ to: string; onClick(e: any): void; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ to: string; onClick(e: any): void; }'. const b6 = ; // incorrect type for optional attribute ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ children: 10; onClick(e: any): void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ children: 10; onClick(e: any): void; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ children: 10; onClick(e: any): void; }'. const b7 = ; // incorrect type for optional attribute ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ children: "hello"; className: true; onClick(e: any): void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ children: "hello"; className: true; onClick(e: any): void; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ children: "hello"; className: true; onClick(e: any): void; }'. const b8 = ; // incorrect type for specified hyphanated name ~~~~~~~~~~~ !!! error TS2322: Type '{ data-format: true; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. diff --git a/tests/baselines/reference/tsxStatelessFunctionComponents1.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponents1.errors.txt index 51e1de2a57e..243f29493bf 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponents1.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponents1.errors.txt @@ -1,24 +1,20 @@ tests/cases/conformance/jsx/file.tsx(19,16): error TS2322: Type '{ naaame: "world"; }' is not assignable to type 'IntrinsicAttributes & { name: string; }'. - Property 'naaame' does not exist on type 'IntrinsicAttributes & { name: string; }'. + Type '{ naaame: "world"; }' is not assignable to type '{ name: string; }'. + Property 'name' is missing in type '{ naaame: "world"; }'. tests/cases/conformance/jsx/file.tsx(27,15): error TS2322: Type '{ name: 42; }' is not assignable to type 'IntrinsicAttributes & { name?: string; }'. Type '{ name: 42; }' is not assignable to type '{ name?: string; }'. Types of property 'name' are incompatible. Type '42' is not assignable to type 'string'. -tests/cases/conformance/jsx/file.tsx(29,15): error TS2322: Type '{ naaaaaaame: "no"; }' is not assignable to type 'IntrinsicAttributes & { name?: string; }'. - Property 'naaaaaaame' does not exist on type 'IntrinsicAttributes & { name?: string; }'. +tests/cases/conformance/jsx/file.tsx(29,15): error TS2339: Property 'naaaaaaame' does not exist on type 'IntrinsicAttributes & { name?: string; }'. tests/cases/conformance/jsx/file.tsx(34,23): error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & { "prop-name": string; }'. Type '{}' is not assignable to type '{ "prop-name": string; }'. Property '"prop-name"' is missing in type '{}'. -tests/cases/conformance/jsx/file.tsx(37,23): error TS2322: Type '{ prop1: true; }' is not assignable to type 'IntrinsicAttributes'. - Property 'prop1' does not exist on type 'IntrinsicAttributes'. -tests/cases/conformance/jsx/file.tsx(38,24): error TS2322: Type '{ ref: (x: any) => any; }' is not assignable to type 'IntrinsicAttributes'. - Property 'ref' does not exist on type 'IntrinsicAttributes'. +tests/cases/conformance/jsx/file.tsx(37,23): error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes'. +tests/cases/conformance/jsx/file.tsx(38,24): error TS2339: Property 'ref' does not exist on type 'IntrinsicAttributes'. tests/cases/conformance/jsx/file.tsx(41,16): error TS1005: ',' expected. -tests/cases/conformance/jsx/file.tsx(45,24): error TS2322: Type '{ prop1: boolean; }' is not assignable to type 'IntrinsicAttributes'. - Property 'prop1' does not exist on type 'IntrinsicAttributes'. -==== tests/cases/conformance/jsx/file.tsx (8 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (7 errors) ==== function EmptyPropSFC() { return

Default Greeting
; } @@ -40,7 +36,8 @@ tests/cases/conformance/jsx/file.tsx(45,24): error TS2322: Type '{ prop1: boolea let b = ; ~~~~~~~~~~~~~~ !!! error TS2322: Type '{ naaame: "world"; }' is not assignable to type 'IntrinsicAttributes & { name: string; }'. -!!! error TS2322: Property 'naaame' does not exist on type 'IntrinsicAttributes & { name: string; }'. +!!! error TS2322: Type '{ naaame: "world"; }' is not assignable to type '{ name: string; }'. +!!! error TS2322: Property 'name' is missing in type '{ naaame: "world"; }'. // OK let c = ; @@ -57,8 +54,7 @@ tests/cases/conformance/jsx/file.tsx(45,24): error TS2322: Type '{ prop1: boolea // Error let f = ; ~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ naaaaaaame: "no"; }' is not assignable to type 'IntrinsicAttributes & { name?: string; }'. -!!! error TS2322: Property 'naaaaaaame' does not exist on type 'IntrinsicAttributes & { name?: string; }'. +!!! error TS2339: Property 'naaaaaaame' does not exist on type 'IntrinsicAttributes & { name?: string; }'. // OK let g = ; @@ -72,12 +68,10 @@ tests/cases/conformance/jsx/file.tsx(45,24): error TS2322: Type '{ prop1: boolea // Error let i = ~~~~~ -!!! error TS2322: Type '{ prop1: true; }' is not assignable to type 'IntrinsicAttributes'. -!!! error TS2322: Property 'prop1' does not exist on type 'IntrinsicAttributes'. +!!! error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes'. let i1 = x.greeting.substr(10)} /> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ ref: (x: any) => any; }' is not assignable to type 'IntrinsicAttributes'. -!!! error TS2322: Property 'ref' does not exist on type 'IntrinsicAttributes'. +!!! error TS2339: Property 'ref' does not exist on type 'IntrinsicAttributes'. let o = { prop1: true; @@ -85,11 +79,8 @@ tests/cases/conformance/jsx/file.tsx(45,24): error TS2322: Type '{ prop1: boolea !!! error TS1005: ',' expected. } - // Error + // OK as access properties are allow when spread let i2 = - ~~~~~~ -!!! error TS2322: Type '{ prop1: boolean; }' is not assignable to type 'IntrinsicAttributes'. -!!! error TS2322: Property 'prop1' does not exist on type 'IntrinsicAttributes'. let o1: any; // OK diff --git a/tests/baselines/reference/tsxStatelessFunctionComponents1.js b/tests/baselines/reference/tsxStatelessFunctionComponents1.js index d19f1ce1073..6ede59b4420 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponents1.js +++ b/tests/baselines/reference/tsxStatelessFunctionComponents1.js @@ -42,7 +42,7 @@ let o = { prop1: true; } -// Error +// OK as access properties are allow when spread let i2 = let o1: any; @@ -93,7 +93,7 @@ var i1 = ; var o = { prop1: true }; -// Error +// OK as access properties are allow when spread var i2 = ; var o1; // OK diff --git a/tests/baselines/reference/tsxStatelessFunctionComponents2.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponents2.errors.txt index 275017ecd82..00e2c4a526c 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponents2.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponents2.errors.txt @@ -1,5 +1,4 @@ -tests/cases/conformance/jsx/file.tsx(19,16): error TS2322: Type '{ ref: "myRef"; }' is not assignable to type 'IntrinsicAttributes & { name?: string; }'. - Property 'ref' does not exist on type 'IntrinsicAttributes & { name?: string; }'. +tests/cases/conformance/jsx/file.tsx(19,16): error TS2339: Property 'ref' does not exist on type 'IntrinsicAttributes & { name?: string; }'. tests/cases/conformance/jsx/file.tsx(25,42): error TS2339: Property 'subtr' does not exist on type 'string'. tests/cases/conformance/jsx/file.tsx(27,33): error TS2339: Property 'notARealProperty' does not exist on type 'BigGreeter'. tests/cases/conformance/jsx/file.tsx(35,26): error TS2339: Property 'propertyNotOnHtmlDivElement' does not exist on type 'HTMLDivElement'. @@ -26,8 +25,7 @@ tests/cases/conformance/jsx/file.tsx(35,26): error TS2339: Property 'propertyNot // Error - not allowed to specify 'ref' on SFCs let c = ; ~~~~~~~~~~~ -!!! error TS2322: Type '{ ref: "myRef"; }' is not assignable to type 'IntrinsicAttributes & { name?: string; }'. -!!! error TS2322: Property 'ref' does not exist on type 'IntrinsicAttributes & { name?: string; }'. +!!! error TS2339: Property 'ref' does not exist on type 'IntrinsicAttributes & { name?: string; }'. // OK - ref is valid for classes diff --git a/tests/baselines/reference/tsxStatelessFunctionComponents3.types b/tests/baselines/reference/tsxStatelessFunctionComponents3.types index 714781058eb..e01c8454aa7 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponents3.types +++ b/tests/baselines/reference/tsxStatelessFunctionComponents3.types @@ -21,8 +21,8 @@ var MainMenu: React.StatelessComponent<{}> = (props) => (
>MainMenu : React.StatelessComponent<{}> >React : any >StatelessComponent : React.StatelessComponent

->(props) => (

Main Menu

) : (props: {}) => JSX.Element ->props : {} +>(props) => (

Main Menu

) : (props: { children?: React.ReactNode; }) => JSX.Element +>props : { children?: React.ReactNode; } >(

Main Menu

) : JSX.Element >

Main Menu

: JSX.Element >div : any @@ -40,7 +40,7 @@ var App: React.StatelessComponent<{ children }> = ({children}) => ( >React : any >StatelessComponent : React.StatelessComponent

>children : any ->({children}) => (

) : ({children}: { children: any; }) => JSX.Element +>({children}) => (
) : ({ children }: { children: any; } & { children?: React.ReactNode; }) => JSX.Element >children : any >(
) : JSX.Element diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments2.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments2.errors.txt index c98c918f3c5..7e940116887 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments2.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments2.errors.txt @@ -1,5 +1,9 @@ -tests/cases/conformance/jsx/file.tsx(8,34): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(13,34): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/jsx/file.tsx(8,34): error TS2322: Type 'T & { ignore-prop: 10; }' is not assignable to type 'IntrinsicAttributes & { prop: number; "ignore-prop": string; }'. + Type 'T & { ignore-prop: 10; }' is not assignable to type '{ prop: number; "ignore-prop": string; }'. + Types of property '"ignore-prop"' are incompatible. + Type '10' is not assignable to type 'string'. +tests/cases/conformance/jsx/file.tsx(13,34): error TS2322: Type 'T' is not assignable to type 'IntrinsicAttributes & { prop: {}; "ignore-prop": string; }'. + Type 'T' is not assignable to type '{ prop: {}; "ignore-prop": string; }'. tests/cases/conformance/jsx/file.tsx(20,19): error TS2322: Type '{ func: (a: number, b: string) => void; }' is not assignable to type 'IntrinsicAttributes & { func: (arg: number) => void; }'. Type '{ func: (a: number, b: string) => void; }' is not assignable to type '{ func: (arg: number) => void; }'. Types of property 'func' are incompatible. @@ -19,15 +23,19 @@ tests/cases/conformance/jsx/file.tsx(31,10): error TS2453: The type argument for // Error function Bar(arg: T) { let a1 = ; - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. + ~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type 'T & { ignore-prop: 10; }' is not assignable to type 'IntrinsicAttributes & { prop: number; "ignore-prop": string; }'. +!!! error TS2322: Type 'T & { ignore-prop: 10; }' is not assignable to type '{ prop: number; "ignore-prop": string; }'. +!!! error TS2322: Types of property '"ignore-prop"' are incompatible. +!!! error TS2322: Type '10' is not assignable to type 'string'. } // Error function Baz(arg: T) { let a0 = ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. +!!! error TS2322: Type 'T' is not assignable to type 'IntrinsicAttributes & { prop: {}; "ignore-prop": string; }'. +!!! error TS2322: Type 'T' is not assignable to type '{ prop: {}; "ignore-prop": string; }'. } declare function Link(l: {func: (arg: U)=>void}): JSX.Element; diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.errors.txt deleted file mode 100644 index fdf65ca1746..00000000000 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.errors.txt +++ /dev/null @@ -1,50 +0,0 @@ -tests/cases/conformance/jsx/file.tsx(9,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(10,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(11,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(12,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(14,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(14,63): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(15,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(15,55): error TS2698: Spread types may only be created from object types. - - -==== tests/cases/conformance/jsx/file.tsx (8 errors) ==== - import React = require('react') - - declare function OverloadComponent(): JSX.Element; - declare function OverloadComponent(attr: {b: U, a?: string, "ignore-prop": boolean}): JSX.Element; - declare function OverloadComponent(attr: {b: U, a: T}): JSX.Element; - - // OK - function Baz(arg1: T, arg2: U) { - let a0 = ; - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - let a1 = ; - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - let a2 = ; - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - let a3 = ; - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - let a4 = ; - let a5 = ; - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - let a6 = ; - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - } - - declare function Link(l: {func: (arg: U)=>void}): JSX.Element; - declare function Link(l: {func: (arg1:U, arg2: string)=>void}): JSX.Element; - function createLink(func: (a: number)=>void) { - let o = - let o1 = {}} />; - } \ No newline at end of file diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.symbols b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.symbols index ebd80b3d262..e93eb374aa7 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.symbols +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.symbols @@ -1,128 +1,127 @@ === tests/cases/conformance/jsx/file.tsx === - import React = require('react') >React : Symbol(React, Decl(file.tsx, 0, 0)) declare function OverloadComponent(): JSX.Element; ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->U : Symbol(U, Decl(file.tsx, 3, 35)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>U : Symbol(U, Decl(file.tsx, 2, 35)) >JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) >Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) declare function OverloadComponent(attr: {b: U, a?: string, "ignore-prop": boolean}): JSX.Element; ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->U : Symbol(U, Decl(file.tsx, 4, 35)) ->attr : Symbol(attr, Decl(file.tsx, 4, 38)) ->b : Symbol(b, Decl(file.tsx, 4, 45)) ->U : Symbol(U, Decl(file.tsx, 4, 35)) ->a : Symbol(a, Decl(file.tsx, 4, 50)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>U : Symbol(U, Decl(file.tsx, 3, 35)) +>attr : Symbol(attr, Decl(file.tsx, 3, 38)) +>b : Symbol(b, Decl(file.tsx, 3, 45)) +>U : Symbol(U, Decl(file.tsx, 3, 35)) +>a : Symbol(a, Decl(file.tsx, 3, 50)) >JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) >Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) declare function OverloadComponent(attr: {b: U, a: T}): JSX.Element; ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->T : Symbol(T, Decl(file.tsx, 5, 35)) ->U : Symbol(U, Decl(file.tsx, 5, 37)) ->attr : Symbol(attr, Decl(file.tsx, 5, 41)) ->b : Symbol(b, Decl(file.tsx, 5, 48)) ->U : Symbol(U, Decl(file.tsx, 5, 37)) ->a : Symbol(a, Decl(file.tsx, 5, 53)) ->T : Symbol(T, Decl(file.tsx, 5, 35)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>T : Symbol(T, Decl(file.tsx, 4, 35)) +>U : Symbol(U, Decl(file.tsx, 4, 37)) +>attr : Symbol(attr, Decl(file.tsx, 4, 41)) +>b : Symbol(b, Decl(file.tsx, 4, 48)) +>U : Symbol(U, Decl(file.tsx, 4, 37)) +>a : Symbol(a, Decl(file.tsx, 4, 53)) +>T : Symbol(T, Decl(file.tsx, 4, 35)) >JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) >Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) // OK function Baz(arg1: T, arg2: U) { ->Baz : Symbol(Baz, Decl(file.tsx, 5, 74)) ->T : Symbol(T, Decl(file.tsx, 8, 13)) ->b : Symbol(b, Decl(file.tsx, 8, 24)) ->U : Symbol(U, Decl(file.tsx, 8, 35)) ->a : Symbol(a, Decl(file.tsx, 8, 47)) ->b : Symbol(b, Decl(file.tsx, 8, 58)) ->arg1 : Symbol(arg1, Decl(file.tsx, 8, 70)) ->T : Symbol(T, Decl(file.tsx, 8, 13)) ->arg2 : Symbol(arg2, Decl(file.tsx, 8, 78)) ->U : Symbol(U, Decl(file.tsx, 8, 35)) +>Baz : Symbol(Baz, Decl(file.tsx, 4, 74)) +>T : Symbol(T, Decl(file.tsx, 7, 13)) +>b : Symbol(b, Decl(file.tsx, 7, 24)) +>U : Symbol(U, Decl(file.tsx, 7, 35)) +>a : Symbol(a, Decl(file.tsx, 7, 47)) +>b : Symbol(b, Decl(file.tsx, 7, 58)) +>arg1 : Symbol(arg1, Decl(file.tsx, 7, 70)) +>T : Symbol(T, Decl(file.tsx, 7, 13)) +>arg2 : Symbol(arg2, Decl(file.tsx, 7, 78)) +>U : Symbol(U, Decl(file.tsx, 7, 35)) let a0 = ; ->a0 : Symbol(a0, Decl(file.tsx, 9, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->arg1 : Symbol(arg1, Decl(file.tsx, 8, 70)) ->a : Symbol(a, Decl(file.tsx, 9, 41)) ->ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 9, 51)) +>a0 : Symbol(a0, Decl(file.tsx, 8, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>arg1 : Symbol(arg1, Decl(file.tsx, 7, 70)) +>a : Symbol(a, Decl(file.tsx, 8, 41)) +>ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 8, 51)) let a1 = ; ->a1 : Symbol(a1, Decl(file.tsx, 10, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->arg2 : Symbol(arg2, Decl(file.tsx, 8, 78)) ->ignore-pro : Symbol(ignore-pro, Decl(file.tsx, 10, 41)) +>a1 : Symbol(a1, Decl(file.tsx, 9, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>arg2 : Symbol(arg2, Decl(file.tsx, 7, 78)) +>ignore-pro : Symbol(ignore-pro, Decl(file.tsx, 9, 41)) let a2 = ; ->a2 : Symbol(a2, Decl(file.tsx, 11, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->arg2 : Symbol(arg2, Decl(file.tsx, 8, 78)) +>a2 : Symbol(a2, Decl(file.tsx, 10, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>arg2 : Symbol(arg2, Decl(file.tsx, 7, 78)) let a3 = ; ->a3 : Symbol(a3, Decl(file.tsx, 12, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->arg1 : Symbol(arg1, Decl(file.tsx, 8, 70)) ->ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 12, 41)) +>a3 : Symbol(a3, Decl(file.tsx, 11, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>arg1 : Symbol(arg1, Decl(file.tsx, 7, 70)) +>ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 11, 41)) let a4 = ; ->a4 : Symbol(a4, Decl(file.tsx, 13, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) +>a4 : Symbol(a4, Decl(file.tsx, 12, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) let a5 = ; ->a5 : Symbol(a5, Decl(file.tsx, 14, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->arg2 : Symbol(arg2, Decl(file.tsx, 8, 78)) ->ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 14, 41)) ->arg1 : Symbol(arg1, Decl(file.tsx, 8, 70)) +>a5 : Symbol(a5, Decl(file.tsx, 13, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>arg2 : Symbol(arg2, Decl(file.tsx, 7, 78)) +>ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 13, 41)) +>arg1 : Symbol(arg1, Decl(file.tsx, 7, 70)) let a6 = ; ->a6 : Symbol(a6, Decl(file.tsx, 15, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->arg2 : Symbol(arg2, Decl(file.tsx, 8, 78)) ->ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 15, 41)) ->arg1 : Symbol(arg1, Decl(file.tsx, 8, 70)) +>a6 : Symbol(a6, Decl(file.tsx, 14, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>arg2 : Symbol(arg2, Decl(file.tsx, 7, 78)) +>ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 14, 41)) +>arg1 : Symbol(arg1, Decl(file.tsx, 7, 70)) } declare function Link(l: {func: (arg: U)=>void}): JSX.Element; ->Link : Symbol(Link, Decl(file.tsx, 16, 1), Decl(file.tsx, 18, 65)) ->U : Symbol(U, Decl(file.tsx, 18, 22)) ->l : Symbol(l, Decl(file.tsx, 18, 25)) ->func : Symbol(func, Decl(file.tsx, 18, 29)) ->arg : Symbol(arg, Decl(file.tsx, 18, 36)) ->U : Symbol(U, Decl(file.tsx, 18, 22)) +>Link : Symbol(Link, Decl(file.tsx, 15, 1), Decl(file.tsx, 17, 65)) +>U : Symbol(U, Decl(file.tsx, 17, 22)) +>l : Symbol(l, Decl(file.tsx, 17, 25)) +>func : Symbol(func, Decl(file.tsx, 17, 29)) +>arg : Symbol(arg, Decl(file.tsx, 17, 36)) +>U : Symbol(U, Decl(file.tsx, 17, 22)) >JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) >Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) declare function Link(l: {func: (arg1:U, arg2: string)=>void}): JSX.Element; ->Link : Symbol(Link, Decl(file.tsx, 16, 1), Decl(file.tsx, 18, 65)) ->U : Symbol(U, Decl(file.tsx, 19, 22)) ->l : Symbol(l, Decl(file.tsx, 19, 25)) ->func : Symbol(func, Decl(file.tsx, 19, 29)) ->arg1 : Symbol(arg1, Decl(file.tsx, 19, 36)) ->U : Symbol(U, Decl(file.tsx, 19, 22)) ->arg2 : Symbol(arg2, Decl(file.tsx, 19, 43)) +>Link : Symbol(Link, Decl(file.tsx, 15, 1), Decl(file.tsx, 17, 65)) +>U : Symbol(U, Decl(file.tsx, 18, 22)) +>l : Symbol(l, Decl(file.tsx, 18, 25)) +>func : Symbol(func, Decl(file.tsx, 18, 29)) +>arg1 : Symbol(arg1, Decl(file.tsx, 18, 36)) +>U : Symbol(U, Decl(file.tsx, 18, 22)) +>arg2 : Symbol(arg2, Decl(file.tsx, 18, 43)) >JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) >Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) function createLink(func: (a: number)=>void) { ->createLink : Symbol(createLink, Decl(file.tsx, 19, 79)) ->func : Symbol(func, Decl(file.tsx, 20, 20)) ->a : Symbol(a, Decl(file.tsx, 20, 27)) +>createLink : Symbol(createLink, Decl(file.tsx, 18, 79)) +>func : Symbol(func, Decl(file.tsx, 19, 20)) +>a : Symbol(a, Decl(file.tsx, 19, 27)) let o = ->o : Symbol(o, Decl(file.tsx, 21, 7)) ->Link : Symbol(Link, Decl(file.tsx, 16, 1), Decl(file.tsx, 18, 65)) ->func : Symbol(func, Decl(file.tsx, 21, 17)) ->func : Symbol(func, Decl(file.tsx, 20, 20)) +>o : Symbol(o, Decl(file.tsx, 20, 7)) +>Link : Symbol(Link, Decl(file.tsx, 15, 1), Decl(file.tsx, 17, 65)) +>func : Symbol(func, Decl(file.tsx, 20, 17)) +>func : Symbol(func, Decl(file.tsx, 19, 20)) let o1 = {}} />; ->o1 : Symbol(o1, Decl(file.tsx, 22, 7)) ->Link : Symbol(Link, Decl(file.tsx, 16, 1), Decl(file.tsx, 18, 65)) ->func : Symbol(func, Decl(file.tsx, 22, 18)) ->a : Symbol(a, Decl(file.tsx, 22, 26)) ->b : Symbol(b, Decl(file.tsx, 22, 35)) +>o1 : Symbol(o1, Decl(file.tsx, 21, 7)) +>Link : Symbol(Link, Decl(file.tsx, 15, 1), Decl(file.tsx, 17, 65)) +>func : Symbol(func, Decl(file.tsx, 21, 18)) +>a : Symbol(a, Decl(file.tsx, 21, 26)) +>b : Symbol(b, Decl(file.tsx, 21, 35)) } diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.types b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.types index f85638d0edd..aa38d2ccf8a 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.types +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.types @@ -1,5 +1,4 @@ === tests/cases/conformance/jsx/file.tsx === - import React = require('react') >React : typeof React @@ -131,8 +130,8 @@ function createLink(func: (a: number)=>void) { >o1 : JSX.Element >{}} /> : JSX.Element >Link : { (l: { func: (arg: U) => void; }): JSX.Element; (l: { func: (arg1: U, arg2: string) => void; }): JSX.Element; } ->func : (a: number, b: string) => void ->(a:number, b:string)=>{} : (a: number, b: string) => void +>func : (a: number, b: string) => any +>(a:number, b:string)=>{} : (a: number, b: string) => any >a : number >b : string } diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments4.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments4.errors.txt index 7988bbdf414..311cfaed86f 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments4.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments4.errors.txt @@ -1,7 +1,12 @@ tests/cases/conformance/jsx/file.tsx(9,33): error TS2322: Type '{ a: number; }' is not assignable to type 'IntrinsicAttributes & { b: {}; a: number; }'. Type '{ a: number; }' is not assignable to type '{ b: {}; a: number; }'. Property 'b' is missing in type '{ a: number; }'. -tests/cases/conformance/jsx/file.tsx(10,33): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/jsx/file.tsx(10,33): error TS2322: Type 'T' is not assignable to type 'IntrinsicAttributes & { b: number; a: {}; }'. + Type '{ b: number; }' is not assignable to type 'IntrinsicAttributes & { b: number; a: {}; }'. + Type '{ b: number; }' is not assignable to type '{ b: number; a: {}; }'. + Type 'T' is not assignable to type '{ b: number; a: {}; }'. + Type '{ b: number; }' is not assignable to type '{ b: number; a: {}; }'. + Property 'a' is missing in type '{ b: number; }'. ==== tests/cases/conformance/jsx/file.tsx (2 errors) ==== @@ -19,6 +24,11 @@ tests/cases/conformance/jsx/file.tsx(10,33): error TS2698: Spread types may only !!! error TS2322: Type '{ a: number; }' is not assignable to type '{ b: {}; a: number; }'. !!! error TS2322: Property 'b' is missing in type '{ a: number; }'. let a2 = // missing a - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type 'T' is not assignable to type 'IntrinsicAttributes & { b: number; a: {}; }'. +!!! error TS2322: Type '{ b: number; }' is not assignable to type 'IntrinsicAttributes & { b: number; a: {}; }'. +!!! error TS2322: Type '{ b: number; }' is not assignable to type '{ b: number; a: {}; }'. +!!! error TS2322: Type 'T' is not assignable to type '{ b: number; a: {}; }'. +!!! error TS2322: Type '{ b: number; }' is not assignable to type '{ b: number; a: {}; }'. +!!! error TS2322: Property 'a' is missing in type '{ b: number; }'. } \ No newline at end of file diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt index 314f8b6cdad..57a2ae556f7 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt @@ -1,37 +1,34 @@ -tests/cases/conformance/jsx/file.tsx(6,25): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(7,25): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(15,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(16,34): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(17,33): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/jsx/file.tsx(15,14): error TS2605: JSX element type 'Element' is not a constructor function for JSX elements. + Property 'render' is missing in type 'Element'. +tests/cases/conformance/jsx/file.tsx(15,15): error TS2453: The type argument for type parameter 'U' cannot be inferred from the usage. Consider specifying the type arguments explicitly. + Type argument candidate 'number' is not a valid type argument because it is not a supertype of candidate '"hello"'. +tests/cases/conformance/jsx/file.tsx(16,42): error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes & { prop: number; }'. -==== tests/cases/conformance/jsx/file.tsx (5 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== import React = require('react') - // Error, can only spread object type declare function Component(l: U): JSX.Element; function createComponent(arg: T) { let a1 = ; - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. let a2 = ; - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. } declare function ComponentSpecific(l: { prop: U }): JSX.Element; declare function ComponentSpecific1(l: { prop: U, "ignore-prop": number }): JSX.Element; - // Error, can only spread object type function Bar(arg: T) { let a1 = ; // U is number - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. let a2 = ; // U is number - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. let a3 = ; // U is "hello" - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2605: JSX element type 'Element' is not a constructor function for JSX elements. +!!! error TS2605: Property 'render' is missing in type 'Element'. + ~~~~~~~~~~~~~~~~~ +!!! error TS2453: The type argument for type parameter 'U' cannot be inferred from the usage. Consider specifying the type arguments explicitly. +!!! error TS2453: Type argument candidate 'number' is not a valid type argument because it is not a supertype of candidate '"hello"'. + let a4 = ; // U is "hello" + ~~~~~~~~~~~~~ +!!! error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes & { prop: number; }'. } \ No newline at end of file diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.js b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.js index b5e215dada3..7e3c8bf35d2 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.js +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.js @@ -1,7 +1,6 @@ //// [file.tsx] import React = require('react') -// Error, can only spread object type declare function Component(l: U): JSX.Element; function createComponent(arg: T) { let a1 = ; @@ -11,11 +10,11 @@ function createComponent(arg: T) { declare function ComponentSpecific(l: { prop: U }): JSX.Element; declare function ComponentSpecific1(l: { prop: U, "ignore-prop": number }): JSX.Element; -// Error, can only spread object type function Bar(arg: T) { let a1 = ; // U is number let a2 = ; // U is number let a3 = ; // U is "hello" + let a4 = ; // U is "hello" } @@ -27,10 +26,10 @@ define(["require", "exports", "react"], function (require, exports, React) { var a1 = ; var a2 = ; } - // Error, can only spread object type function Bar(arg) { var a1 = ; // U is number var a2 = ; // U is number var a3 = ; // U is "hello" + var a4 = ; // U is "hello" } }); diff --git a/tests/baselines/reference/tsxUnionElementType4.errors.txt b/tests/baselines/reference/tsxUnionElementType4.errors.txt index 7c94a08b6ef..4658b566cc7 100644 --- a/tests/baselines/reference/tsxUnionElementType4.errors.txt +++ b/tests/baselines/reference/tsxUnionElementType4.errors.txt @@ -3,10 +3,8 @@ tests/cases/conformance/jsx/file.tsx(32,17): error TS2322: Type '{ x: true; }' i Type '{ x: true; }' is not assignable to type '{ x: string; }'. Types of property 'x' are incompatible. Type 'true' is not assignable to type 'string'. -tests/cases/conformance/jsx/file.tsx(33,21): error TS2322: Type '{ x: 10; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. - Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. -tests/cases/conformance/jsx/file.tsx(34,22): error TS2322: Type '{ prop: true; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. - Property 'prop' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. +tests/cases/conformance/jsx/file.tsx(33,21): error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. +tests/cases/conformance/jsx/file.tsx(34,22): error TS2339: Property 'prop' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. ==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== @@ -50,10 +48,8 @@ tests/cases/conformance/jsx/file.tsx(34,22): error TS2322: Type '{ prop: true; } !!! error TS2322: Type 'true' is not assignable to type 'string'. let b = ~~~~~~ -!!! error TS2322: Type '{ x: 10; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. -!!! error TS2322: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. +!!! error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. let c = ; ~~~~ -!!! error TS2322: Type '{ prop: true; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. -!!! error TS2322: Property 'prop' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. +!!! error TS2339: Property 'prop' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxUnionElementType6.errors.txt b/tests/baselines/reference/tsxUnionElementType6.errors.txt index 1f31fb21f26..cac96565b80 100644 --- a/tests/baselines/reference/tsxUnionElementType6.errors.txt +++ b/tests/baselines/reference/tsxUnionElementType6.errors.txt @@ -1,5 +1,4 @@ -tests/cases/conformance/jsx/file.tsx(18,23): error TS2322: Type '{ x: true; }' is not assignable to type 'IntrinsicAttributes'. - Property 'x' does not exist on type 'IntrinsicAttributes'. +tests/cases/conformance/jsx/file.tsx(18,23): error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes'. tests/cases/conformance/jsx/file.tsx(19,27): error TS2322: Type '{ x: "hi"; }' is not assignable to type 'IntrinsicAttributes & { x: boolean; }'. Type '{ x: "hi"; }' is not assignable to type '{ x: boolean; }'. Types of property 'x' are incompatible. @@ -32,8 +31,7 @@ tests/cases/conformance/jsx/file.tsx(21,27): error TS2322: Type '{}' is not assi // Error let a = ; ~ -!!! error TS2322: Type '{ x: true; }' is not assignable to type 'IntrinsicAttributes'. -!!! error TS2322: Property 'x' does not exist on type 'IntrinsicAttributes'. +!!! error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes'. let b = ; ~~~~~~ !!! error TS2322: Type '{ x: "hi"; }' is not assignable to type 'IntrinsicAttributes & { x: boolean; }'. diff --git a/tests/baselines/reference/typeArgumentInferenceWithObjectLiteral.errors.txt b/tests/baselines/reference/typeArgumentInferenceWithObjectLiteral.errors.txt index e82e7e020d0..c1352bedb9b 100644 --- a/tests/baselines/reference/typeArgumentInferenceWithObjectLiteral.errors.txt +++ b/tests/baselines/reference/typeArgumentInferenceWithObjectLiteral.errors.txt @@ -1,10 +1,8 @@ -tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithObjectLiteral.ts(30,10): error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly. - Type argument candidate 'E1' is not a valid type argument because it is not a supertype of candidate '0'. tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithObjectLiteral.ts(35,10): error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly. Type argument candidate 'E1' is not a valid type argument because it is not a supertype of candidate 'E2'. -==== tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithObjectLiteral.ts (2 errors) ==== +==== tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithObjectLiteral.ts (1 errors) ==== interface Computed { read(): T; write(value: T); @@ -35,9 +33,6 @@ tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithObjec var v1 = f1({ w: x => x, r: () => 0 }, 0); var v1 = f1({ w: x => x, r: () => 0 }, E1.X); var v1 = f1({ w: x => x, r: () => E1.X }, 0); - ~~ -!!! error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly. -!!! error TS2453: Type argument candidate 'E1' is not a valid type argument because it is not a supertype of candidate '0'. var v2: E1; var v2 = f1({ w: x => x, r: () => E1.X }, E1.X); diff --git a/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt b/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt index b2d9e3f8aaf..5c916331950 100644 --- a/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt +++ b/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt @@ -1,19 +1,19 @@ -tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(2,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(2,13): error TS2558: Expected 0 type arguments, but got 1. tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(3,15): error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. -tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(4,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(4,13): error TS2558: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts (3 errors) ==== function foo(f: (v: T) => U) { var r1 = f(1); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var r2 = f(1); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. var r3 = f(null); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var r4 = f(null); } \ No newline at end of file diff --git a/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt b/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt index 7d99934f5ea..0df5d91865d 100644 --- a/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt +++ b/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/typeAssertionToGenericFunctionType.ts(5,13): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/typeAssertionToGenericFunctionType.ts(6,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/typeAssertionToGenericFunctionType.ts(6,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/typeAssertionToGenericFunctionType.ts (2 errors) ==== @@ -12,4 +12,4 @@ tests/cases/compiler/typeAssertionToGenericFunctionType.ts(6,1): error TS2346: S !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. x.b(); // error ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/typeAssertions.errors.txt b/tests/baselines/reference/typeAssertions.errors.txt index c840e016083..45f20437860 100644 --- a/tests/baselines/reference/typeAssertions.errors.txt +++ b/tests/baselines/reference/typeAssertions.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(5,5): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(5,5): error TS2558: Expected 0 type arguments, but got 1. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(31,12): error TS2352: Type 'SomeOther' cannot be converted to type 'SomeBase'. Property 'p' is missing in type 'SomeOther'. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(35,15): error TS2352: Type 'SomeOther' cannot be converted to type 'SomeDerived'. @@ -11,7 +11,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,5): erro tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,14): error TS1005: '>' expected. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,14): error TS2304: Cannot find name 'is'. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,17): error TS1005: ')' expected. -tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,17): error TS2304: Cannot find name 'string'. +tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,17): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,48): error TS1005: ';' expected. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(45,2): error TS2322: Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'. @@ -19,7 +19,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,32): err tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,41): error TS1005: ')' expected. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,41): error TS2304: Cannot find name 'is'. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,44): error TS1005: ';' expected. -tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,44): error TS2304: Cannot find name 'string'. +tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,44): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): error TS1005: ';' expected. @@ -30,7 +30,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err fn1(fn2(4)); // Error ~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var a: any; var s: string; @@ -91,7 +91,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err ~~~~~~ !!! error TS1005: ')' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. str = numOrStr; // Error, no narrowing occurred @@ -110,7 +110,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err ~~~~~~ !!! error TS1005: ';' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. } diff --git a/tests/baselines/reference/typeGuardFunctionErrors.errors.txt b/tests/baselines/reference/typeGuardFunctionErrors.errors.txt index d50d86afa5e..b9d884939bd 100644 --- a/tests/baselines/reference/typeGuardFunctionErrors.errors.txt +++ b/tests/baselines/reference/typeGuardFunctionErrors.errors.txt @@ -19,9 +19,9 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(41,56) Type 'number' is not assignable to type 'string'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(45,56): error TS2677: A type predicate's type must be assignable to its parameter's type. Type 'T[]' is not assignable to type 'string'. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(59,7): error TS2339: Property 'propB' does not exist on type 'A'. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(64,7): error TS2339: Property 'propB' does not exist on type 'A'. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(69,7): error TS2339: Property 'propB' does not exist on type 'A'. +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(59,7): error TS2551: Property 'propB' does not exist on type 'A'. Did you mean 'propA'? +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(64,7): error TS2551: Property 'propB' does not exist on type 'A'. Did you mean 'propA'? +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(69,7): error TS2551: Property 'propB' does not exist on type 'A'. Did you mean 'propA'? tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(74,46): error TS2345: Argument of type '(p1: any) => p1 is C' is not assignable to parameter of type '(p1: any) => p1 is B'. Type predicate 'p1 is C' is not assignable to 'p1 is B'. Type 'C' is not assignable to type 'B'. @@ -163,21 +163,21 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(136,39 if (isB(b)) { a.propB; ~~~~~ -!!! error TS2339: Property 'propB' does not exist on type 'A'. +!!! error TS2551: Property 'propB' does not exist on type 'A'. Did you mean 'propA'? } // Parameter index and argument index for the type guard target is not matching. if (funA(0, a)) { a.propB; // Error ~~~~~ -!!! error TS2339: Property 'propB' does not exist on type 'A'. +!!! error TS2551: Property 'propB' does not exist on type 'A'. Did you mean 'propA'? } // No type guard in if statement if (hasNoTypeGuard(a)) { a.propB; ~~~~~ -!!! error TS2339: Property 'propB' does not exist on type 'A'. +!!! error TS2551: Property 'propB' does not exist on type 'A'. Did you mean 'propA'? } // Type predicate type is not assignable diff --git a/tests/baselines/reference/typeGuardsAsAssertions.js b/tests/baselines/reference/typeGuardsAsAssertions.js index 8c9b2048514..692af453c0c 100644 --- a/tests/baselines/reference/typeGuardsAsAssertions.js +++ b/tests/baselines/reference/typeGuardsAsAssertions.js @@ -119,6 +119,11 @@ function f6() { x = ""; x!.slice(); } + +function f7() { + let x: string; + x!.slice(); +} //// [typeGuardsAsAssertions.js] @@ -227,3 +232,7 @@ function f6() { x = ""; x.slice(); } +function f7() { + var x; + x.slice(); +} diff --git a/tests/baselines/reference/typeGuardsAsAssertions.symbols b/tests/baselines/reference/typeGuardsAsAssertions.symbols index 71c02412a12..346418871db 100644 --- a/tests/baselines/reference/typeGuardsAsAssertions.symbols +++ b/tests/baselines/reference/typeGuardsAsAssertions.symbols @@ -312,3 +312,15 @@ function f6() { >slice : Symbol(String.slice, Decl(lib.d.ts, --, --)) } +function f7() { +>f7 : Symbol(f7, Decl(typeGuardsAsAssertions.ts, 119, 1)) + + let x: string; +>x : Symbol(x, Decl(typeGuardsAsAssertions.ts, 122, 7)) + + x!.slice(); +>x!.slice : Symbol(String.slice, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(typeGuardsAsAssertions.ts, 122, 7)) +>slice : Symbol(String.slice, Decl(lib.d.ts, --, --)) +} + diff --git a/tests/baselines/reference/typeGuardsAsAssertions.types b/tests/baselines/reference/typeGuardsAsAssertions.types index 09378bcee54..bd11b4a6f20 100644 --- a/tests/baselines/reference/typeGuardsAsAssertions.types +++ b/tests/baselines/reference/typeGuardsAsAssertions.types @@ -382,3 +382,17 @@ function f6() { >slice : (start?: number | undefined, end?: number | undefined) => string } +function f7() { +>f7 : () => void + + let x: string; +>x : string + + x!.slice(); +>x!.slice() : string +>x!.slice : (start?: number | undefined, end?: number | undefined) => string +>x! : string +>x : string +>slice : (start?: number | undefined, end?: number | undefined) => string +} + diff --git a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt index 31db51bf57e..b93be614f74 100644 --- a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt +++ b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt @@ -22,8 +22,8 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(160,11): error TS2339: Property 'foo2' does not exist on type 'G1'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(166,11): error TS2339: Property 'foo2' does not exist on type 'G1'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(182,11): error TS2339: Property 'bar' does not exist on type 'H'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(187,11): error TS2339: Property 'foo1' does not exist on type 'H'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(188,11): error TS2339: Property 'foo2' does not exist on type 'H'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(187,11): error TS2551: Property 'foo1' does not exist on type 'H'. Did you mean 'foo'? +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(188,11): error TS2551: Property 'foo2' does not exist on type 'H'. Did you mean 'foo'? ==== tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts (20 errors) ==== @@ -257,10 +257,10 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru if (obj16 instanceof H) { obj16.foo1; ~~~~ -!!! error TS2339: Property 'foo1' does not exist on type 'H'. +!!! error TS2551: Property 'foo1' does not exist on type 'H'. Did you mean 'foo'? obj16.foo2; ~~~~ -!!! error TS2339: Property 'foo2' does not exist on type 'H'. +!!! error TS2551: Property 'foo2' does not exist on type 'H'. Did you mean 'foo'? } var obj17: any; diff --git a/tests/baselines/reference/typeParametersAndParametersInComputedNames.errors.txt b/tests/baselines/reference/typeParametersAndParametersInComputedNames.errors.txt index 872a0a10923..f01f7520cba 100644 --- a/tests/baselines/reference/typeParametersAndParametersInComputedNames.errors.txt +++ b/tests/baselines/reference/typeParametersAndParametersInComputedNames.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/typeParametersAndParametersInComputedNames.ts(6,10): error TS2304: Cannot find name 'T'. -tests/cases/compiler/typeParametersAndParametersInComputedNames.ts(6,13): error TS2304: Cannot find name 'a'. +tests/cases/compiler/typeParametersAndParametersInComputedNames.ts(6,13): error TS2552: Cannot find name 'a'. Did you mean 'A'? ==== tests/cases/compiler/typeParametersAndParametersInComputedNames.ts (2 errors) ==== @@ -12,6 +12,6 @@ tests/cases/compiler/typeParametersAndParametersInComputedNames.ts(6,13): error ~ !!! error TS2304: Cannot find name 'T'. ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? } } \ No newline at end of file diff --git a/tests/baselines/reference/typeVariableTypeGuards.js b/tests/baselines/reference/typeVariableTypeGuards.js new file mode 100644 index 00000000000..8525bde0f77 --- /dev/null +++ b/tests/baselines/reference/typeVariableTypeGuards.js @@ -0,0 +1,158 @@ +//// [typeVariableTypeGuards.ts] +// Repro from #14091 + +interface Foo { + foo(): void +} + +class A

> { + props: Readonly

+ doSomething() { + this.props.foo && this.props.foo() + } +} + +// Repro from #14415 + +interface Banana { + color: 'yellow'; +} + +class Monkey { + a: T; + render() { + if (this.a) { + this.a.color; + } + } +} + +interface BigBanana extends Banana { +} + +class BigMonkey extends Monkey { + render() { + if (this.a) { + this.a.color; + } + } +} + +// Another repro + +type Item = { + (): string; + x: string; +} + +function f1(obj: T) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} + +function f2(obj: T | undefined) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} + +function f3(obj: T | null) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} + +function f4(obj: T | undefined, x: number) { + if (obj) { + obj[x].length; + } +} + +function f5(obj: T | undefined, key: K) { + if (obj) { + obj[key]; + } +} + + +//// [typeVariableTypeGuards.js] +"use strict"; +// Repro from #14091 +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var A = (function () { + function A() { + } + A.prototype.doSomething = function () { + this.props.foo && this.props.foo(); + }; + return A; +}()); +var Monkey = (function () { + function Monkey() { + } + Monkey.prototype.render = function () { + if (this.a) { + this.a.color; + } + }; + return Monkey; +}()); +var BigMonkey = (function (_super) { + __extends(BigMonkey, _super); + function BigMonkey() { + return _super !== null && _super.apply(this, arguments) || this; + } + BigMonkey.prototype.render = function () { + if (this.a) { + this.a.color; + } + }; + return BigMonkey; +}(Monkey)); +function f1(obj) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} +function f2(obj) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} +function f3(obj) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} +function f4(obj, x) { + if (obj) { + obj[x].length; + } +} +function f5(obj, key) { + if (obj) { + obj[key]; + } +} diff --git a/tests/baselines/reference/typeVariableTypeGuards.symbols b/tests/baselines/reference/typeVariableTypeGuards.symbols new file mode 100644 index 00000000000..fa94cfd9462 --- /dev/null +++ b/tests/baselines/reference/typeVariableTypeGuards.symbols @@ -0,0 +1,221 @@ +=== tests/cases/compiler/typeVariableTypeGuards.ts === +// Repro from #14091 + +interface Foo { +>Foo : Symbol(Foo, Decl(typeVariableTypeGuards.ts, 0, 0)) + + foo(): void +>foo : Symbol(Foo.foo, Decl(typeVariableTypeGuards.ts, 2, 15)) +} + +class A

> { +>A : Symbol(A, Decl(typeVariableTypeGuards.ts, 4, 1)) +>P : Symbol(P, Decl(typeVariableTypeGuards.ts, 6, 8)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>Foo : Symbol(Foo, Decl(typeVariableTypeGuards.ts, 0, 0)) + + props: Readonly

+>props : Symbol(A.props, Decl(typeVariableTypeGuards.ts, 6, 33)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>P : Symbol(P, Decl(typeVariableTypeGuards.ts, 6, 8)) + + doSomething() { +>doSomething : Symbol(A.doSomething, Decl(typeVariableTypeGuards.ts, 7, 22)) + + this.props.foo && this.props.foo() +>this.props.foo : Symbol(foo) +>this.props : Symbol(A.props, Decl(typeVariableTypeGuards.ts, 6, 33)) +>this : Symbol(A, Decl(typeVariableTypeGuards.ts, 4, 1)) +>props : Symbol(A.props, Decl(typeVariableTypeGuards.ts, 6, 33)) +>foo : Symbol(foo) +>this.props.foo : Symbol(foo) +>this.props : Symbol(A.props, Decl(typeVariableTypeGuards.ts, 6, 33)) +>this : Symbol(A, Decl(typeVariableTypeGuards.ts, 4, 1)) +>props : Symbol(A.props, Decl(typeVariableTypeGuards.ts, 6, 33)) +>foo : Symbol(foo) + } +} + +// Repro from #14415 + +interface Banana { +>Banana : Symbol(Banana, Decl(typeVariableTypeGuards.ts, 11, 1)) + + color: 'yellow'; +>color : Symbol(Banana.color, Decl(typeVariableTypeGuards.ts, 15, 18)) +} + +class Monkey { +>Monkey : Symbol(Monkey, Decl(typeVariableTypeGuards.ts, 17, 1)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 19, 13)) +>Banana : Symbol(Banana, Decl(typeVariableTypeGuards.ts, 11, 1)) + + a: T; +>a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 19, 13)) + + render() { +>render : Symbol(Monkey.render, Decl(typeVariableTypeGuards.ts, 20, 9)) + + if (this.a) { +>this.a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>this : Symbol(Monkey, Decl(typeVariableTypeGuards.ts, 17, 1)) +>a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) + + this.a.color; +>this.a.color : Symbol(Banana.color, Decl(typeVariableTypeGuards.ts, 15, 18)) +>this.a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>this : Symbol(Monkey, Decl(typeVariableTypeGuards.ts, 17, 1)) +>a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>color : Symbol(Banana.color, Decl(typeVariableTypeGuards.ts, 15, 18)) + } + } +} + +interface BigBanana extends Banana { +>BigBanana : Symbol(BigBanana, Decl(typeVariableTypeGuards.ts, 26, 1)) +>Banana : Symbol(Banana, Decl(typeVariableTypeGuards.ts, 11, 1)) +} + +class BigMonkey extends Monkey { +>BigMonkey : Symbol(BigMonkey, Decl(typeVariableTypeGuards.ts, 29, 1)) +>Monkey : Symbol(Monkey, Decl(typeVariableTypeGuards.ts, 17, 1)) +>BigBanana : Symbol(BigBanana, Decl(typeVariableTypeGuards.ts, 26, 1)) + + render() { +>render : Symbol(BigMonkey.render, Decl(typeVariableTypeGuards.ts, 31, 43)) + + if (this.a) { +>this.a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>this : Symbol(BigMonkey, Decl(typeVariableTypeGuards.ts, 29, 1)) +>a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) + + this.a.color; +>this.a.color : Symbol(Banana.color, Decl(typeVariableTypeGuards.ts, 15, 18)) +>this.a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>this : Symbol(BigMonkey, Decl(typeVariableTypeGuards.ts, 29, 1)) +>a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>color : Symbol(Banana.color, Decl(typeVariableTypeGuards.ts, 15, 18)) + } + } +} + +// Another repro + +type Item = { +>Item : Symbol(Item, Decl(typeVariableTypeGuards.ts, 37, 1)) + + (): string; + x: string; +>x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) +} + +function f1(obj: T) { +>f1 : Symbol(f1, Decl(typeVariableTypeGuards.ts, 44, 1)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 46, 12)) +>Item : Symbol(Item, Decl(typeVariableTypeGuards.ts, 37, 1)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 46, 40)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 46, 12)) + + if (obj) { +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 46, 40)) + + obj.x; +>obj.x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 46, 40)) +>x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) + + obj["x"]; +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 46, 40)) +>"x" : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) + + obj(); +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 46, 40)) + } +} + +function f2(obj: T | undefined) { +>f2 : Symbol(f2, Decl(typeVariableTypeGuards.ts, 52, 1)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 54, 12)) +>Item : Symbol(Item, Decl(typeVariableTypeGuards.ts, 37, 1)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 54, 40)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 54, 12)) + + if (obj) { +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 54, 40)) + + obj.x; +>obj.x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 54, 40)) +>x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) + + obj["x"]; +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 54, 40)) +>"x" : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) + + obj(); +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 54, 40)) + } +} + +function f3(obj: T | null) { +>f3 : Symbol(f3, Decl(typeVariableTypeGuards.ts, 60, 1)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 62, 12)) +>Item : Symbol(Item, Decl(typeVariableTypeGuards.ts, 37, 1)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 62, 40)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 62, 12)) + + if (obj) { +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 62, 40)) + + obj.x; +>obj.x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 62, 40)) +>x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) + + obj["x"]; +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 62, 40)) +>"x" : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) + + obj(); +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 62, 40)) + } +} + +function f4(obj: T | undefined, x: number) { +>f4 : Symbol(f4, Decl(typeVariableTypeGuards.ts, 68, 1)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 70, 12)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 70, 44)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 70, 12)) +>x : Symbol(x, Decl(typeVariableTypeGuards.ts, 70, 63)) + + if (obj) { +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 70, 44)) + + obj[x].length; +>obj[x].length : Symbol(String.length, Decl(lib.d.ts, --, --)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 70, 44)) +>x : Symbol(x, Decl(typeVariableTypeGuards.ts, 70, 63)) +>length : Symbol(String.length, Decl(lib.d.ts, --, --)) + } +} + +function f5(obj: T | undefined, key: K) { +>f5 : Symbol(f5, Decl(typeVariableTypeGuards.ts, 74, 1)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 76, 12)) +>K : Symbol(K, Decl(typeVariableTypeGuards.ts, 76, 14)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 76, 12)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 76, 34)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 76, 12)) +>key : Symbol(key, Decl(typeVariableTypeGuards.ts, 76, 53)) +>K : Symbol(K, Decl(typeVariableTypeGuards.ts, 76, 14)) + + if (obj) { +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 76, 34)) + + obj[key]; +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 76, 34)) +>key : Symbol(key, Decl(typeVariableTypeGuards.ts, 76, 53)) + } +} + diff --git a/tests/baselines/reference/typeVariableTypeGuards.types b/tests/baselines/reference/typeVariableTypeGuards.types new file mode 100644 index 00000000000..bfcf851648a --- /dev/null +++ b/tests/baselines/reference/typeVariableTypeGuards.types @@ -0,0 +1,232 @@ +=== tests/cases/compiler/typeVariableTypeGuards.ts === +// Repro from #14091 + +interface Foo { +>Foo : Foo + + foo(): void +>foo : () => void +} + +class A

> { +>A : A

+>P : P +>Partial : Partial +>Foo : Foo + + props: Readonly

+>props : Readonly

+>Readonly : Readonly +>P : P + + doSomething() { +>doSomething : () => void + + this.props.foo && this.props.foo() +>this.props.foo && this.props.foo() : void +>this.props.foo : P["foo"] +>this.props : Readonly

+>this : this +>props : Readonly

+>foo : P["foo"] +>this.props.foo() : void +>this.props.foo : () => void +>this.props : Readonly

+>this : this +>props : Readonly

+>foo : () => void + } +} + +// Repro from #14415 + +interface Banana { +>Banana : Banana + + color: 'yellow'; +>color : "yellow" +} + +class Monkey { +>Monkey : Monkey +>T : T +>Banana : Banana + + a: T; +>a : T +>T : T + + render() { +>render : () => void + + if (this.a) { +>this.a : T +>this : this +>a : T + + this.a.color; +>this.a.color : "yellow" +>this.a : Banana +>this : this +>a : Banana +>color : "yellow" + } + } +} + +interface BigBanana extends Banana { +>BigBanana : BigBanana +>Banana : Banana +} + +class BigMonkey extends Monkey { +>BigMonkey : BigMonkey +>Monkey : Monkey +>BigBanana : BigBanana + + render() { +>render : () => void + + if (this.a) { +>this.a : BigBanana +>this : this +>a : BigBanana + + this.a.color; +>this.a.color : "yellow" +>this.a : BigBanana +>this : this +>a : BigBanana +>color : "yellow" + } + } +} + +// Another repro + +type Item = { +>Item : Item + + (): string; + x: string; +>x : string +} + +function f1(obj: T) { +>f1 : (obj: T) => void +>T : T +>Item : Item +>obj : T +>T : T + + if (obj) { +>obj : T + + obj.x; +>obj.x : string +>obj : Item +>x : string + + obj["x"]; +>obj["x"] : string +>obj : Item +>"x" : "x" + + obj(); +>obj() : string +>obj : Item + } +} + +function f2(obj: T | undefined) { +>f2 : (obj: T | undefined) => void +>T : T +>Item : Item +>obj : T | undefined +>T : T + + if (obj) { +>obj : T | undefined + + obj.x; +>obj.x : string +>obj : Item +>x : string + + obj["x"]; +>obj["x"] : string +>obj : Item +>"x" : "x" + + obj(); +>obj() : string +>obj : Item + } +} + +function f3(obj: T | null) { +>f3 : (obj: T | null) => void +>T : T +>Item : Item +>obj : T | null +>T : T +>null : null + + if (obj) { +>obj : T | null + + obj.x; +>obj.x : string +>obj : Item +>x : string + + obj["x"]; +>obj["x"] : string +>obj : Item +>"x" : "x" + + obj(); +>obj() : string +>obj : Item + } +} + +function f4(obj: T | undefined, x: number) { +>f4 : (obj: T | undefined, x: number) => void +>T : T +>obj : T | undefined +>T : T +>x : number + + if (obj) { +>obj : T | undefined + + obj[x].length; +>obj[x].length : number +>obj[x] : string +>obj : string[] +>x : number +>length : number + } +} + +function f5(obj: T | undefined, key: K) { +>f5 : (obj: T | undefined, key: K) => void +>T : T +>K : K +>T : T +>obj : T | undefined +>T : T +>key : K +>K : K + + if (obj) { +>obj : T | undefined + + obj[key]; +>obj[key] : T[K] +>obj : T +>key : K + } +} + diff --git a/tests/baselines/reference/typesWithPrivateConstructor.js b/tests/baselines/reference/typesWithPrivateConstructor.js index be58c77339d..e5c59b99e93 100644 --- a/tests/baselines/reference/typesWithPrivateConstructor.js +++ b/tests/baselines/reference/typesWithPrivateConstructor.js @@ -38,7 +38,7 @@ declare class C { declare var c: any; declare var r: () => void; declare class C2 { - private constructor(x); + private constructor(); } declare var c2: any; declare var r2: (x: number) => void; diff --git a/tests/baselines/reference/typesWithPublicConstructor.errors.txt b/tests/baselines/reference/typesWithPublicConstructor.errors.txt index 17abc57f6df..d3b03740bf2 100644 --- a/tests/baselines/reference/typesWithPublicConstructor.errors.txt +++ b/tests/baselines/reference/typesWithPublicConstructor.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/types/members/typesWithPublicConstructor.ts(8,5): error TS2322: Type 'Function' is not assignable to type '() => void'. Type 'Function' provides no match for the signature '(): void'. -tests/cases/conformance/types/members/typesWithPublicConstructor.ts(15,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/members/typesWithPublicConstructor.ts(15,10): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/conformance/types/members/typesWithPublicConstructor.ts (2 errors) ==== @@ -23,5 +23,5 @@ tests/cases/conformance/types/members/typesWithPublicConstructor.ts(15,10): erro var c2 = new C2(); ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var r2: (x: number) => void = c2.constructor; \ No newline at end of file diff --git a/tests/baselines/reference/undeclaredVarEmit.errors.txt b/tests/baselines/reference/undeclaredVarEmit.errors.txt index a95323aa362..bbf508ab005 100644 --- a/tests/baselines/reference/undeclaredVarEmit.errors.txt +++ b/tests/baselines/reference/undeclaredVarEmit.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/undeclaredVarEmit.ts(1,1): error TS7028: Unused label. -tests/cases/compiler/undeclaredVarEmit.ts(1,4): error TS2304: Cannot find name 'number'. +tests/cases/compiler/undeclaredVarEmit.ts(1,4): error TS2693: 'number' only refers to a type, but is being used as a value here. ==== tests/cases/compiler/undeclaredVarEmit.ts (2 errors) ==== @@ -7,4 +7,4 @@ tests/cases/compiler/undeclaredVarEmit.ts(1,4): error TS2304: Cannot find name ' ~ !!! error TS7028: Unused label. ~~~~~~ -!!! error TS2304: Cannot find name 'number'. \ No newline at end of file +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. \ No newline at end of file diff --git a/tests/baselines/reference/unicodeStringLiteral.js b/tests/baselines/reference/unicodeStringLiteral.js new file mode 100644 index 00000000000..c69f7aa7e99 --- /dev/null +++ b/tests/baselines/reference/unicodeStringLiteral.js @@ -0,0 +1,5 @@ +//// [unicodeStringLiteral.ts] +var ੳ = "Ü­ਲĭ"; + +//// [unicodeStringLiteral.js] +var ੳ = "Ü­ਲĭ"; diff --git a/tests/baselines/reference/unicodeStringLiteral.symbols b/tests/baselines/reference/unicodeStringLiteral.symbols new file mode 100644 index 00000000000..f48111c0608 --- /dev/null +++ b/tests/baselines/reference/unicodeStringLiteral.symbols @@ -0,0 +1,4 @@ +=== tests/cases/compiler/unicodeStringLiteral.ts === +var ੳ = "Ü­ਲĭ"; +>ੳ : Symbol(ੳ, Decl(unicodeStringLiteral.ts, 0, 3)) + diff --git a/tests/baselines/reference/unicodeStringLiteral.types b/tests/baselines/reference/unicodeStringLiteral.types new file mode 100644 index 00000000000..e98f5987ed3 --- /dev/null +++ b/tests/baselines/reference/unicodeStringLiteral.types @@ -0,0 +1,5 @@ +=== tests/cases/compiler/unicodeStringLiteral.ts === +var ੳ = "Ü­ਲĭ"; +>ੳ : string +>"Ü­ਲĭ" : "Ü­ਲ\u000Eĭ" + diff --git a/tests/baselines/reference/unionSubtypeIfEveryConstituentTypeIsSubtype.errors.txt b/tests/baselines/reference/unionSubtypeIfEveryConstituentTypeIsSubtype.errors.txt index 013b5d9a990..ddf5da8881a 100644 --- a/tests/baselines/reference/unionSubtypeIfEveryConstituentTypeIsSubtype.errors.txt +++ b/tests/baselines/reference/unionSubtypeIfEveryConstituentTypeIsSubtype.errors.txt @@ -1,37 +1,36 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(15,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'number'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(21,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'string'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(22,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'string'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(22,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'string'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(28,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'boolean'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(29,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'boolean'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(29,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'boolean'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(35,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'Date'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(36,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'Date'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(36,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'Date'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(42,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'RegExp'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(43,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'RegExp'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(43,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'RegExp'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(49,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type '{ bar: number; }'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(50,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type '{ bar: number; }'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(50,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type '{ bar: number; }'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(56,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'number[]'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(57,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'number[]'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(57,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'number[]'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(63,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'I8'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(64,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'I8'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(64,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'I8'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(70,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'A'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(71,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'A'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(71,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'A'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(77,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'A2'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(78,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'A2'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(78,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'A2'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(84,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type '(x: any) => number'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(85,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type '(x: any) => number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(85,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type '(x: any) => number'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(91,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type '(x: T) => T'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(92,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type '(x: T) => T'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(92,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type '(x: T) => T'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(99,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'E2'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(100,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'E2'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(110,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'typeof f'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(111,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'typeof f'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(111,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'typeof f'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(121,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'typeof c'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(122,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'typeof c'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(122,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'typeof c'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(128,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'T'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(129,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'T'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(129,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'T'. -==== tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts (31 errors) ==== +==== tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts (30 errors) ==== enum e { e1, e2 @@ -59,7 +58,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'string'. foo2: e | number; // error e and number both not subtype of string ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'string'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'string'. } // error cases @@ -70,7 +69,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'boolean'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'boolean'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'boolean'. } @@ -81,7 +80,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'Date'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'Date'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'Date'. } @@ -92,7 +91,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'RegExp'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'RegExp'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'RegExp'. } @@ -103,7 +102,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type '{ bar: number; }'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type '{ bar: number; }'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type '{ bar: number; }'. } @@ -114,7 +113,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'number[]'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'number[]'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'number[]'. } @@ -125,7 +124,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'I8'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'I8'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'I8'. } class A { foo: number; } @@ -136,7 +135,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'A'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'A'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'A'. } class A2 { foo: T; } @@ -147,7 +146,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'A2'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'A2'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'A2'. } @@ -158,7 +157,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type '(x: any) => number'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type '(x: any) => number'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type '(x: any) => number'. } @@ -169,7 +168,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type '(x: T) => T'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type '(x: T) => T'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type '(x: T) => T'. } @@ -180,8 +179,6 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'E2'. foo2: e | number; - ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'E2'. } @@ -196,7 +193,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'typeof f'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'typeof f'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'typeof f'. } @@ -211,7 +208,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'typeof c'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'typeof c'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'typeof c'. } @@ -222,7 +219,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'T'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'T'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'T'. } interface I19 { diff --git a/tests/baselines/reference/unionTypeCallSignatures.errors.txt b/tests/baselines/reference/unionTypeCallSignatures.errors.txt index 0398c0cec47..c123dc8da56 100644 --- a/tests/baselines/reference/unionTypeCallSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeCallSignatures.errors.txt @@ -1,34 +1,34 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(9,43): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(10,29): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(15,29): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(16,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(16,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(19,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: number) => number) | ((a: string) => Date)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(20,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: number) => number) | ((a: string) => Date)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(21,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: number) => number) | ((a: string) => Date)' has no compatible call signatures. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(24,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(24,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(26,36): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(29,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: string) => string) | ((a: string, b: number) => number)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(30,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: string) => string) | ((a: string, b: number) => number)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(31,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: string) => string) | ((a: string, b: number) => number)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(36,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(37,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(40,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(37,12): error TS2554: Expected 1-2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(40,12): error TS2554: Expected 2 arguments, but got 1. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(42,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(43,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(47,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(48,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(49,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(43,12): error TS2554: Expected 2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(47,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(48,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(49,12): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(55,45): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(56,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(59,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(61,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(56,12): error TS2555: Expected at least 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(59,12): error TS2554: Expected 2 arguments, but got 1. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(61,12): error TS2554: Expected 2 arguments, but got 3. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(62,45): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(63,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(67,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(68,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(69,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(70,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(63,12): error TS2554: Expected 2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(67,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(68,12): error TS2554: Expected 1 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(69,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(70,12): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2554: Expected 2 arguments, but got 1. ==== tests/cases/conformance/types/union/unionTypeCallSignatures.ts (31 errors) ==== @@ -55,7 +55,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 !!! error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. unionOfDifferentReturnType1(); // error missing parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var unionOfDifferentParameterTypes: { (a: number): number; } | { (a: string): Date; }; unionOfDifferentParameterTypes(10);// error - no call signatures @@ -71,7 +71,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 var unionOfDifferentNumberOfSignatures: { (a: number): number; } | { (a: number): Date; (a: string): boolean; }; unionOfDifferentNumberOfSignatures(); // error - no call signatures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. unionOfDifferentNumberOfSignatures(10); // error - no call signatures unionOfDifferentNumberOfSignatures("hello"); // error - no call signatures ~~~~~~~ @@ -96,31 +96,31 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = unionWithOptionalParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 0. var unionWithOptionalParameter2: { (a: string, b?: number): string; } | { (a: string, b: number): number }; strOrNum = unionWithOptionalParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 1. strOrNum = unionWithOptionalParameter2('hello', 10); // error no call signature strOrNum = unionWithOptionalParameter2('hello', "hello"); // error no call signature ~~~~~~~ !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = unionWithOptionalParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 0. var unionWithOptionalParameter3: { (a: string, b?: number): string; } | { (a: string): number; }; strOrNum = unionWithOptionalParameter3('hello'); strOrNum = unionWithOptionalParameter3('hello', 10); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = unionWithOptionalParameter3('hello', "hello"); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = unionWithOptionalParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var unionWithRestParameter1: { (a: string, ...b: number[]): string; } | { (a: string, ...b: number[]): number }; strOrNum = unionWithRestParameter1('hello'); @@ -131,41 +131,41 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = unionWithRestParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2555: Expected at least 1 arguments, but got 0. var unionWithRestParameter2: { (a: string, ...b: number[]): string; } | { (a: string, b: number): number }; strOrNum = unionWithRestParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 1. strOrNum = unionWithRestParameter2('hello', 10); // error no call signature strOrNum = unionWithRestParameter2('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 3. strOrNum = unionWithRestParameter2('hello', "hello"); // error no call signature ~~~~~~~ !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = unionWithRestParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 0. var unionWithRestParameter3: { (a: string, ...b: number[]): string; } | { (a: string): number }; strOrNum = unionWithRestParameter3('hello'); strOrNum = unionWithRestParameter3('hello', 10); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = unionWithRestParameter3('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 3. strOrNum = unionWithRestParameter3('hello', "hello"); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = unionWithRestParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var unionWithRestParameter4: { (...a: string[]): string; } | { (a: string, b: string): number; }; strOrNum = unionWithRestParameter4("hello"); // error supplied parameters do not match any call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 1. strOrNum = unionWithRestParameter4("hello", "world"); \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeCallSignatures4.errors.txt b/tests/baselines/reference/unionTypeCallSignatures4.errors.txt index 585906a6b5a..1d9c3d272f0 100644 --- a/tests/baselines/reference/unionTypeCallSignatures4.errors.txt +++ b/tests/baselines/reference/unionTypeCallSignatures4.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(10,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(20,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(23,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(10,1): error TS2554: Expected 1-2 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(20,1): error TS2554: Expected 1-2 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(23,1): error TS2554: Expected 2 arguments, but got 1. +tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2554: Expected 2 arguments, but got 3. ==== tests/cases/conformance/types/union/unionTypeCallSignatures4.ts (4 errors) ==== @@ -16,7 +16,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2 f12("a", "b"); f12("a", "b", "c"); // error ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 3. var f34: F3 | F4; f34("a"); @@ -28,14 +28,14 @@ tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2 f1234("a", "b"); f1234("a", "b", "c"); // error ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 3. var f12345: F1 | F2 | F3 | F4 | F5; f12345("a"); // error ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 1. f12345("a", "b"); f12345("a", "b", "c"); // error ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt index 813f7701ea8..8b4c6f9aa0c 100644 --- a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt @@ -1,33 +1,33 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(9,47): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(10,33): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(15,33): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(16,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(16,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(19,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(20,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(21,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(24,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(24,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(26,40): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(29,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(30,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(31,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(36,53): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(37,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(40,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(37,12): error TS2554: Expected 1-2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(40,12): error TS2554: Expected 2 arguments, but got 1. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(42,53): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(43,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(47,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(48,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(49,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(43,12): error TS2554: Expected 2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(47,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(48,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(49,12): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(55,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(56,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(59,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(61,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(56,12): error TS2555: Expected at least 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(59,12): error TS2554: Expected 2 arguments, but got 1. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(61,12): error TS2554: Expected 2 arguments, but got 3. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(62,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(63,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(67,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(68,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(69,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(63,12): error TS2554: Expected 2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(67,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(68,12): error TS2554: Expected 1 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(69,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/conformance/types/union/unionTypeConstructSignatures.ts (30 errors) ==== @@ -54,7 +54,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro !!! error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. new unionOfDifferentReturnType1(); // error missing parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var unionOfDifferentParameterTypes: { new (a: number): number; } | { new (a: string): Date; }; new unionOfDifferentParameterTypes(10);// error - no call signatures @@ -70,7 +70,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro var unionOfDifferentNumberOfSignatures: { new (a: number): number; } | { new (a: number): Date; new (a: string): boolean; }; new unionOfDifferentNumberOfSignatures(); // error - no call signatures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. new unionOfDifferentNumberOfSignatures(10); // error - no call signatures new unionOfDifferentNumberOfSignatures("hello"); // error - no call signatures ~~~~~~~ @@ -95,31 +95,31 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = new unionWithOptionalParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-2 arguments, but got 0. var unionWithOptionalParameter2: { new (a: string, b?: number): string; } | { new (a: string, b: number): number }; strOrNum = new unionWithOptionalParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 1. strOrNum = new unionWithOptionalParameter2('hello', 10); // error no call signature strOrNum = new unionWithOptionalParameter2('hello', "hello"); // error no call signature ~~~~~~~ !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = new unionWithOptionalParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 0. var unionWithOptionalParameter3: { new (a: string, b?: number): string; } | { new (a: string): number; }; strOrNum = new unionWithOptionalParameter3('hello'); // error no call signature strOrNum = new unionWithOptionalParameter3('hello', 10); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = new unionWithOptionalParameter3('hello', "hello"); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = new unionWithOptionalParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 0. var unionWithRestParameter1: { new (a: string, ...b: number[]): string; } | { new (a: string, ...b: number[]): number }; strOrNum = new unionWithRestParameter1('hello'); @@ -130,34 +130,34 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = new unionWithRestParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2555: Expected at least 1 arguments, but got 0. var unionWithRestParameter2: { new (a: string, ...b: number[]): string; } | { new (a: string, b: number): number }; strOrNum = new unionWithRestParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 1. strOrNum = new unionWithRestParameter2('hello', 10); // error no call signature strOrNum = new unionWithRestParameter2('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 3. strOrNum = new unionWithRestParameter2('hello', "hello"); // error no call signature ~~~~~~~ !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = new unionWithRestParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 arguments, but got 0. var unionWithRestParameter3: { new (a: string, ...b: number[]): string; } | { new (a: string): number }; strOrNum = new unionWithRestParameter3('hello'); // error no call signature strOrNum = new unionWithRestParameter3('hello', 10); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = new unionWithRestParameter3('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 3. strOrNum = new unionWithRestParameter3('hello', "hello"); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = new unionWithRestParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt b/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt index 399a37c32fd..6b6594fc1ed 100644 --- a/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt +++ b/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt @@ -1,13 +1,13 @@ -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(3,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(3,10): error TS2558: Expected 0 type arguments, but got 1. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(5,10): error TS2347: Untyped function calls may not accept type arguments. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(8,10): error TS2347: Untyped function calls may not accept type arguments. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(10,7): error TS2420: Class 'C' incorrectly implements interface 'Function'. Property 'apply' is missing in type 'C'. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(18,10): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'C' has no compatible call signatures. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(22,10): error TS2347: Untyped function calls may not accept type arguments. -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(28,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(35,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(28,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(35,1): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2558: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts (9 errors) ==== @@ -15,7 +15,7 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var x = function () { return; }; var r1 = x(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. var y: any = x; var r2 = y(); ~~~~~~~~~~~ @@ -53,7 +53,7 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var z: I; var r6 = z(1); // error ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. interface callable2 { (a: T): T; @@ -62,7 +62,7 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var c4: callable2; c4(1); ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. interface callable3 { (a: T): T; } @@ -70,6 +70,6 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var c5: callable3; c5(1); // error ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2558: Expected 0 type arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/unusedInvalidTypeArguments.errors.txt b/tests/baselines/reference/unusedInvalidTypeArguments.errors.txt new file mode 100644 index 00000000000..d524c717980 --- /dev/null +++ b/tests/baselines/reference/unusedInvalidTypeArguments.errors.txt @@ -0,0 +1,78 @@ +/call.ts(1,21): error TS2307: Cannot find module 'unknown'. +/callAny.ts(3,1): error TS2347: Untyped function calls may not accept type arguments. +/callAny.ts(4,1): error TS2347: Untyped function calls may not accept type arguments. +/callAny.ts(4,3): error TS2304: Cannot find name 'InvalidReference'. +/classReference.ts(4,24): error TS2315: Type 'C' is not generic. +/interface.ts(1,21): error TS2307: Cannot find module 'unknown'. +/new.ts(1,21): error TS2307: Cannot find module 'unkown'. +/super.ts(1,22): error TS2307: Cannot find module 'unknown'. +/super.ts(8,17): error TS2304: Cannot find name 'InvalidReference'. +/typeReference.ts(6,17): error TS2315: Type 'U' is not generic. + + +==== /typeReference.ts (1 errors) ==== + // Tests that types are marked as used, even if used in places that don't accept type arguments. + + + type N = number; + type U = number; + export type Z = U; + ~~~~ +!!! error TS2315: Type 'U' is not generic. + +==== /classReference.ts (1 errors) ==== + type N = number; + class C { } + // This uses getTypeFromClassOrInterfaceReference instead of getTypeFromTypeAliasReference. + export class D extends C {} + ~~~~ +!!! error TS2315: Type 'C' is not generic. + +==== /interface.ts (1 errors) ==== + import { Foo } from "unknown"; + ~~~~~~~~~ +!!! error TS2307: Cannot find module 'unknown'. + export interface I { x: Foo; } + +==== /call.ts (1 errors) ==== + import { foo } from "unknown"; + ~~~~~~~~~ +!!! error TS2307: Cannot find module 'unknown'. + type T = number; + foo(); + +==== /new.ts (1 errors) ==== + import { Foo } from "unkown"; + ~~~~~~~~ +!!! error TS2307: Cannot find module 'unkown'. + type T = number; + new Foo(); + +==== /callAny.ts (3 errors) ==== + declare var g: any; + type U = number; + g(); + ~~~~~~ +!!! error TS2347: Untyped function calls may not accept type arguments. + g(); // Should get error for type argument + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2347: Untyped function calls may not accept type arguments. + ~~~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'InvalidReference'. + +==== /super.ts (2 errors) ==== + import { A, B } from "unknown"; + ~~~~~~~~~ +!!! error TS2307: Cannot find module 'unknown'. + + type T = number; + + export class C extends A { + m() { + super.m(1); + super.m(); // Should get error for type argument + ~~~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'InvalidReference'. + } + } + \ No newline at end of file diff --git a/tests/baselines/reference/unusedInvalidTypeArguments.js b/tests/baselines/reference/unusedInvalidTypeArguments.js new file mode 100644 index 00000000000..9f32181a0fb --- /dev/null +++ b/tests/baselines/reference/unusedInvalidTypeArguments.js @@ -0,0 +1,122 @@ +//// [tests/cases/compiler/unusedInvalidTypeArguments.ts] //// + +//// [typeReference.ts] +// Tests that types are marked as used, even if used in places that don't accept type arguments. + + +type N = number; +type U = number; +export type Z = U; + +//// [classReference.ts] +type N = number; +class C { } +// This uses getTypeFromClassOrInterfaceReference instead of getTypeFromTypeAliasReference. +export class D extends C {} + +//// [interface.ts] +import { Foo } from "unknown"; +export interface I { x: Foo; } + +//// [call.ts] +import { foo } from "unknown"; +type T = number; +foo(); + +//// [new.ts] +import { Foo } from "unkown"; +type T = number; +new Foo(); + +//// [callAny.ts] +declare var g: any; +type U = number; +g(); +g(); // Should get error for type argument + +//// [super.ts] +import { A, B } from "unknown"; + +type T = number; + +export class C extends A { + m() { + super.m(1); + super.m(); // Should get error for type argument + } +} + + +//// [typeReference.js] +"use strict"; +// Tests that types are marked as used, even if used in places that don't accept type arguments. +exports.__esModule = true; +//// [classReference.js] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var C = (function () { + function C() { + } + return C; +}()); +// This uses getTypeFromClassOrInterfaceReference instead of getTypeFromTypeAliasReference. +var D = (function (_super) { + __extends(D, _super); + function D() { + return _super !== null && _super.apply(this, arguments) || this; + } + return D; +}(C)); +exports.D = D; +//// [interface.js] +"use strict"; +exports.__esModule = true; +//// [call.js] +"use strict"; +exports.__esModule = true; +var unknown_1 = require("unknown"); +unknown_1.foo(); +//// [new.js] +"use strict"; +exports.__esModule = true; +var unkown_1 = require("unkown"); +new unkown_1.Foo(); +//// [callAny.js] +g(); +g(); // Should get error for type argument +//// [super.js] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var unknown_1 = require("unknown"); +var C = (function (_super) { + __extends(C, _super); + function C() { + return _super !== null && _super.apply(this, arguments) || this; + } + C.prototype.m = function () { + _super.prototype.m.call(this, 1); + _super.prototype.m.call(this); // Should get error for type argument + }; + return C; +}(unknown_1.A)); +exports.C = C; diff --git a/tests/cases/compiler/APISample_compile.ts b/tests/cases/compiler/APISample_compile.ts index b60c53685aa..c49d2a7b122 100644 --- a/tests/cases/compiler/APISample_compile.ts +++ b/tests/cases/compiler/APISample_compile.ts @@ -4,7 +4,7 @@ // @strictNullChecks:true /* - * Note: This test is a public API sample. The sample sources can be found + * Note: This test is a public API sample. The sample sources can be found at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#a-minimal-compiler * Please log a "breaking change" issue for any API breaking change affecting this issue */ @@ -22,8 +22,12 @@ export function compile(fileNames: string[], options: ts.CompilerOptions): void var allDiagnostics = ts.getPreEmitDiagnostics(program); allDiagnostics.forEach(diagnostic => { - var { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); var message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + if (!diagnostic.file) { + console.log(message); + return; + } + var { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); }); @@ -35,4 +39,4 @@ export function compile(fileNames: string[], options: ts.CompilerOptions): void compile(process.argv.slice(2), { noEmitOnError: true, noImplicitAny: true, target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS -}); \ No newline at end of file +}); diff --git a/tests/cases/compiler/APISample_watcher.ts b/tests/cases/compiler/APISample_watcher.ts index 07922bd35c7..3e8ce3d8d63 100644 --- a/tests/cases/compiler/APISample_watcher.ts +++ b/tests/cases/compiler/APISample_watcher.ts @@ -4,7 +4,7 @@ // @strictNullChecks:true /* - * Note: This test is a public API sample. The sample sources can be found + * Note: This test is a public API sample. The sample sources can be found at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#incremental-build-support-using-the-language-services * Please log a "breaking change" issue for any API breaking change affecting this issue */ @@ -95,7 +95,7 @@ function watch(rootFileNames: string[], options: ts.CompilerOptions) { allDiagnostics.forEach(diagnostic => { let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); if (diagnostic.file) { - let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); + let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); console.log(` Error ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); } else { @@ -110,4 +110,4 @@ const currentDirectoryFiles = fs.readdirSync(process.cwd()). filter(fileName=> fileName.length >= 3 && fileName.substr(fileName.length - 3, 3) === ".ts"); // Start the watcher -watch(currentDirectoryFiles, { module: ts.ModuleKind.CommonJS }); \ No newline at end of file +watch(currentDirectoryFiles, { module: ts.ModuleKind.CommonJS }); diff --git a/tests/cases/compiler/blockScopedNamespaceDifferentFile.ts b/tests/cases/compiler/blockScopedNamespaceDifferentFile.ts new file mode 100644 index 00000000000..4a9fe4a2a85 --- /dev/null +++ b/tests/cases/compiler/blockScopedNamespaceDifferentFile.ts @@ -0,0 +1,22 @@ +// @target: es5 +// @outFile: out.js +// @module: amd + +// #15734 failed when test.ts comes before typings.d.ts +// @Filename: test.ts +namespace C { + export class Name { + static funcData = A.AA.func(); + static someConst = A.AA.foo; + + constructor(parameters) {} + } +} + +// @Filename: typings.d.ts +declare namespace A { + namespace AA { + function func(): number; + const foo = ""; + } +} diff --git a/tests/cases/compiler/capturedVarInLoop.ts b/tests/cases/compiler/capturedVarInLoop.ts new file mode 100644 index 00000000000..65cc5620f83 --- /dev/null +++ b/tests/cases/compiler/capturedVarInLoop.ts @@ -0,0 +1,6 @@ +// @target: es5 +for (var i = 0; i < 10; i++) { + var str = 'x', len = str.length; + let lambda1 = (y) => { }; + let lambda2 = () => lambda1(len); +} \ No newline at end of file diff --git a/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts b/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts new file mode 100644 index 00000000000..58844d98fd8 --- /dev/null +++ b/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts @@ -0,0 +1,19 @@ +// @Filename: weird.js +// @allowJs: true +// @checkJs: true +// @strict: true +// @noEmit: true +// @out: foo.js +someFunction(function(BaseClass) { + 'use strict'; + const DEFAULT_MESSAGE = "nop!"; + class Hello extends BaseClass { + constructor() { + super(); + this.foo = "bar"; + } + _render(error) { + const message = error.message || DEFAULT_MESSAGE; + } + } +}); diff --git a/tests/cases/compiler/checkJsFiles7.ts b/tests/cases/compiler/checkJsFiles7.ts new file mode 100644 index 00000000000..2c3d528da00 --- /dev/null +++ b/tests/cases/compiler/checkJsFiles7.ts @@ -0,0 +1,12 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true +// @fileName: a.js +class C { + constructor() { + /** @type {boolean} */ + this.a = true; + this.a = !!this.a; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/commentsAfterCaseClauses1.ts b/tests/cases/compiler/commentsAfterCaseClauses1.ts new file mode 100644 index 00000000000..8b494161584 --- /dev/null +++ b/tests/cases/compiler/commentsAfterCaseClauses1.ts @@ -0,0 +1,14 @@ +function getSecurity(level) { + switch(level){ + case 0: // Zero + case 1: // one + case 2: // two + return "Hi"; + case 3: // three + case 4 : // four + return "hello"; + case 5: // five + default: // default + return "world"; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/commentsAfterCaseClauses2.ts b/tests/cases/compiler/commentsAfterCaseClauses2.ts new file mode 100644 index 00000000000..9c35b80894e --- /dev/null +++ b/tests/cases/compiler/commentsAfterCaseClauses2.ts @@ -0,0 +1,17 @@ +function getSecurity(level) { + switch(level){ + case 0: // Zero + case 1: // one + case 2: // two + // Leading comments + return "Hi"; + case 3: // three + case 4: // four + return "hello"; + case 5: // five + default: // default + return "world"; + // Comment After + } /*Comment 1*/ // Comment After 1 + // Comment After 2 +} \ No newline at end of file diff --git a/tests/cases/compiler/commentsAfterCaseClauses3.ts b/tests/cases/compiler/commentsAfterCaseClauses3.ts new file mode 100644 index 00000000000..894e743c2e7 --- /dev/null +++ b/tests/cases/compiler/commentsAfterCaseClauses3.ts @@ -0,0 +1,16 @@ +function getSecurity(level) { + switch(level){ + case 0: /*Zero*/ + case 1: /*One*/ + case 2: /*two*/ + // Leading comments + return "Hi"; + case 3: /*three*/ + case 4: /*four*/ + return "hello"; + case 5: /*five*/ + default: /*six*/ + return "world"; + } + +} \ No newline at end of file diff --git a/tests/cases/compiler/declarationEmitClassPrivateConstructor.ts b/tests/cases/compiler/declarationEmitClassPrivateConstructor.ts new file mode 100644 index 00000000000..d77360496c9 --- /dev/null +++ b/tests/cases/compiler/declarationEmitClassPrivateConstructor.ts @@ -0,0 +1,22 @@ +// @target: es5 +// @module: commonjs +// @declaration: true + +interface PrivateInterface { +} + +export class ExportedClass1 { + private constructor(data: PrivateInterface) { } +} + +export class ExportedClass2 { + private constructor(private data: PrivateInterface) { } +} + +export class ExportedClass3 { + private constructor(private data: PrivateInterface, private n: number) { } +} + +export class ExportedClass4 { + private constructor(private data: PrivateInterface, public n:number) { } +} \ No newline at end of file diff --git a/tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts b/tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts new file mode 100644 index 00000000000..900ece84f8e --- /dev/null +++ b/tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts @@ -0,0 +1,15 @@ +// @target: es5 +// @module: commonjs +// @declaration: true + +interface PrivateInterface { +} + +export class ExportedClass1 { + private constructor(public data: PrivateInterface) { } +} + + +export class ExportedClass2 { + protected constructor(data: PrivateInterface) { } +} \ No newline at end of file diff --git a/tests/cases/compiler/declarationEmitExpressionInExtends5.ts b/tests/cases/compiler/declarationEmitExpressionInExtends5.ts new file mode 100644 index 00000000000..5057ade7570 --- /dev/null +++ b/tests/cases/compiler/declarationEmitExpressionInExtends5.ts @@ -0,0 +1,20 @@ +// @declaration: true +namespace Test +{ + export interface IFace + { + } + + export class SomeClass implements IFace + { + } + + export class Derived extends getClass() + { + } + + export function getClass() : new() => T + { + return SomeClass as (new() => T); + } +} diff --git a/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts b/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts new file mode 100644 index 00000000000..f99bcbd7efd --- /dev/null +++ b/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts @@ -0,0 +1,30 @@ +// @declaration: true +export var simpleExample = class { + static getTags() { } + tags() { } +} +export var circularReference = class C { + static getTags(c: C): C { return c } + tags(c: C): C { return c } +} + +// repro from #15066 +export class FooItem { + foo(): void { } + name?: string; +} + +export type Constructor = new(...args: any[]) => T; +export function WithTags>(Base: T) { + return class extends Base { + static getTags(): void { } + tags(): void { } + } +} + +export class Test extends WithTags(FooItem) {} + +const test = new Test(); + +Test.getTags() +test.tags(); diff --git a/tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts b/tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts new file mode 100644 index 00000000000..3175f2afce7 --- /dev/null +++ b/tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts @@ -0,0 +1,29 @@ +// @declaration: true +export var noPrivates = class { + static getTags() { } + tags() { } + private static ps = -1 + private p = 12 +} + +// altered repro from #15066 to add private property +export class FooItem { + foo(): void { } + name?: string; + private property = "capitalism" +} + +export type Constructor = new(...args: any[]) => T; +export function WithTags>(Base: T) { + return class extends Base { + static getTags(): void { } + tags(): void { } + } +} + +export class Test extends WithTags(FooItem) {} + +const test = new Test(); + +Test.getTags() +test.tags(); diff --git a/tests/cases/compiler/exportDefaultAbstractClass.ts b/tests/cases/compiler/exportDefaultAbstractClass.ts index 584e95b6b03..31877911622 100644 --- a/tests/cases/compiler/exportDefaultAbstractClass.ts +++ b/tests/cases/compiler/exportDefaultAbstractClass.ts @@ -1,5 +1,11 @@ -// @filename: a.ts -export default abstract class A {} - -// @filename: b.ts -import A from './a' +// @Filename: a.ts +export default abstract class A { a: number; } + +class B extends A {} +new B().a.toExponential(); + +// @Filename: b.ts +import A from './a'; + +class C extends A {} +new C().a.toExponential(); \ No newline at end of file diff --git a/tests/cases/compiler/exportDefaultInterface.ts b/tests/cases/compiler/exportDefaultInterface.ts new file mode 100644 index 00000000000..c7bbbe8019e --- /dev/null +++ b/tests/cases/compiler/exportDefaultInterface.ts @@ -0,0 +1,11 @@ +// @Filename: a.ts +export default interface A { value: number; } + +var a: A; +a.value.toExponential(); + +// @Filename: b.ts +import A from './a'; + +var a: A; +a.value.toExponential(); \ No newline at end of file diff --git a/tests/cases/compiler/importDeclTypes.ts b/tests/cases/compiler/importDeclTypes.ts new file mode 100644 index 00000000000..ab7ba50c236 --- /dev/null +++ b/tests/cases/compiler/importDeclTypes.ts @@ -0,0 +1,9 @@ + +// @filename: /node_modules/@types/foo-bar/index.d.ts +export interface Foo { + bar: string; +} + +// This should error +// @filename: /a.ts +import { Foo } from "@types/foo-bar"; diff --git a/tests/cases/compiler/importHelpersNoHelpersForAsyncGenerators.ts b/tests/cases/compiler/importHelpersNoHelpersForAsyncGenerators.ts new file mode 100644 index 00000000000..a42b5148b43 --- /dev/null +++ b/tests/cases/compiler/importHelpersNoHelpersForAsyncGenerators.ts @@ -0,0 +1,16 @@ +// @importHelpers: true +// @target: es5 +// @module: commonjs +// @lib: esnext +// @moduleResolution: classic +// @experimentalDecorators: true +// @emitDecoratorMetadata: true +// @filename: main.ts +export async function * f() { + await 1; + yield 2; + yield* [3]; +} + +// @filename: tslib.d.ts +export {} diff --git a/tests/cases/compiler/isolatedModulesDontElideReExportStar.ts b/tests/cases/compiler/isolatedModulesDontElideReExportStar.ts new file mode 100644 index 00000000000..37a851a6292 --- /dev/null +++ b/tests/cases/compiler/isolatedModulesDontElideReExportStar.ts @@ -0,0 +1,8 @@ +// @isolatedModules: true +// @target: es6 + +// @filename: /a.ts +export type T = number; + +// @filename: /b.ts +export * from "./a"; diff --git a/tests/cases/compiler/isolatedModulesReExportType.ts b/tests/cases/compiler/isolatedModulesReExportType.ts new file mode 100644 index 00000000000..d1e05af6c83 --- /dev/null +++ b/tests/cases/compiler/isolatedModulesReExportType.ts @@ -0,0 +1,31 @@ +// @isolatedModules: true + +// @Filename: /exportT.ts +export type T = number; + +// @Filename: /exportValue.ts +export class C {} + +// @Filename: /exportEqualsT.ts +declare type T = number; +export = T; + + +// @Filename: /user.ts +// Error, can't re-export something that's only a type. +export { T } from "./exportT"; +export import T2 = require("./exportEqualsT"); + +// OK, has a value side +export { C } from "./exportValue"; + +// OK, even though the namespace it exports is only types. +import * as NS from "./exportT"; +export { NS }; + +// OK, syntactically clear that a type is being re-exported. +export type T3 = T; + +// Error, not clear (to an isolated module) whether `T4` is a type. +import { T } from "./exportT"; +export { T as T4 }; diff --git a/tests/cases/compiler/jsdocInTypeScript.ts b/tests/cases/compiler/jsdocInTypeScript.ts index ba9e8dbcbff..08cfb6d5af5 100644 --- a/tests/cases/compiler/jsdocInTypeScript.ts +++ b/tests/cases/compiler/jsdocInTypeScript.ts @@ -7,3 +7,24 @@ class T { } x.prop; + +// Just to be sure that @property has no impact either. +/** + * @typedef {Object} MyType + * @property {string} yes + */ +declare const myType: MyType; // should error, no such type + +// @param type has no effect. +/** + * @param {number} x + * @returns string + */ +function f(x: boolean) { return x * 2; } // Should error +// Should fail, because it takes a boolean and returns a number +f(1); f(true).length; + +// @type has no effect either. +/** @type {{ x?: number }} */ +const z = {}; +z.x = 1; diff --git a/tests/cases/compiler/maximum10SpellingSuggestions.ts b/tests/cases/compiler/maximum10SpellingSuggestions.ts new file mode 100644 index 00000000000..7aa27dc1e2a --- /dev/null +++ b/tests/cases/compiler/maximum10SpellingSuggestions.ts @@ -0,0 +1,5 @@ +// 10 bobs on the first line +// the last two bobs should not have did-you-mean spelling suggestions +var blob; +bob; bob; bob; bob; bob; bob; bob; bob; bob; bob; +bob; bob; diff --git a/tests/cases/compiler/metadataOfClassFromAlias.ts b/tests/cases/compiler/metadataOfClassFromAlias.ts new file mode 100644 index 00000000000..c7407c8d766 --- /dev/null +++ b/tests/cases/compiler/metadataOfClassFromAlias.ts @@ -0,0 +1,18 @@ +// @experimentalDecorators: true +// @emitDecoratorMetadata: true +// @target: es5 +// @module: commonjs + +// @filename: auxiliry.ts +export class SomeClass { + field: string; +} + +//@filename: test.ts +import { SomeClass } from './auxiliry'; +function annotation(): PropertyDecorator { + return (target: any): void => { }; +} +export class ClassA { + @annotation() array: SomeClass | null; +} \ No newline at end of file diff --git a/tests/cases/compiler/metadataOfClassFromAlias2.ts b/tests/cases/compiler/metadataOfClassFromAlias2.ts new file mode 100644 index 00000000000..05c44d9c677 --- /dev/null +++ b/tests/cases/compiler/metadataOfClassFromAlias2.ts @@ -0,0 +1,18 @@ +// @experimentalDecorators: true +// @emitDecoratorMetadata: true +// @target: es5 +// @module: commonjs + +// @filename: auxiliry.ts +export class SomeClass { + field: string; +} + +//@filename: test.ts +import { SomeClass } from './auxiliry'; +function annotation(): PropertyDecorator { + return (target: any): void => { }; +} +export class ClassA { + @annotation() array: SomeClass | null | string; +} \ No newline at end of file diff --git a/tests/cases/compiler/objectLiteralFreshnessWithSpread.ts b/tests/cases/compiler/objectLiteralFreshnessWithSpread.ts new file mode 100644 index 00000000000..7e8044e064a --- /dev/null +++ b/tests/cases/compiler/objectLiteralFreshnessWithSpread.ts @@ -0,0 +1,2 @@ +let x = { b: 1, extra: 2 } +let xx: { a, b } = { a: 1, ...x, z: 3 } // error for 'z', no error for 'extra' diff --git a/tests/cases/compiler/pathMappingBasedModuleResolution_withExtensionInName.ts b/tests/cases/compiler/pathMappingBasedModuleResolution_withExtensionInName.ts new file mode 100644 index 00000000000..675003fe142 --- /dev/null +++ b/tests/cases/compiler/pathMappingBasedModuleResolution_withExtensionInName.ts @@ -0,0 +1,23 @@ +// @traceResolution: true +// @module: commonjs +// @noImplicitReferences: true + +// @filename: /tsconfig.json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "*": ["foo/*"] + } + } +} + +// @filename: /foo/zone.js/index.d.ts +export const x: number; + +// @filename: /foo/zone.tsx/index.d.ts +export const y: number; + +// @filename: /a.ts +import { x } from "zone.js"; +import { y } from "zone.tsx"; diff --git a/tests/cases/compiler/typeVariableTypeGuards.ts b/tests/cases/compiler/typeVariableTypeGuards.ts new file mode 100644 index 00000000000..0a4221c93a0 --- /dev/null +++ b/tests/cases/compiler/typeVariableTypeGuards.ts @@ -0,0 +1,83 @@ +// @strict: true + +// Repro from #14091 + +interface Foo { + foo(): void +} + +class A

> { + props: Readonly

+ doSomething() { + this.props.foo && this.props.foo() + } +} + +// Repro from #14415 + +interface Banana { + color: 'yellow'; +} + +class Monkey { + a: T; + render() { + if (this.a) { + this.a.color; + } + } +} + +interface BigBanana extends Banana { +} + +class BigMonkey extends Monkey { + render() { + if (this.a) { + this.a.color; + } + } +} + +// Another repro + +type Item = { + (): string; + x: string; +} + +function f1(obj: T) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} + +function f2(obj: T | undefined) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} + +function f3(obj: T | null) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} + +function f4(obj: T | undefined, x: number) { + if (obj) { + obj[x].length; + } +} + +function f5(obj: T | undefined, key: K) { + if (obj) { + obj[key]; + } +} diff --git a/tests/cases/compiler/unicodeStringLiteral.ts b/tests/cases/compiler/unicodeStringLiteral.ts new file mode 100644 index 00000000000..fa2e1283309 --- /dev/null +++ b/tests/cases/compiler/unicodeStringLiteral.ts @@ -0,0 +1 @@ +var ੳ = "Ü­ਲĭ"; \ No newline at end of file diff --git a/tests/cases/compiler/unusedInvalidTypeArguments.ts b/tests/cases/compiler/unusedInvalidTypeArguments.ts new file mode 100644 index 00000000000..3f4d56f8d30 --- /dev/null +++ b/tests/cases/compiler/unusedInvalidTypeArguments.ts @@ -0,0 +1,46 @@ +// Tests that types are marked as used, even if used in places that don't accept type arguments. + +// @noUnusedLocals: true + +// @Filename: /typeReference.ts +type N = number; +type U = number; +export type Z = U; + +// @Filename: /classReference.ts +type N = number; +class C { } +// This uses getTypeFromClassOrInterfaceReference instead of getTypeFromTypeAliasReference. +export class D extends C {} + +// @Filename: /interface.ts +import { Foo } from "unknown"; +export interface I { x: Foo; } + +// @Filename: /call.ts +import { foo } from "unknown"; +type T = number; +foo(); + +// @Filename: /new.ts +import { Foo } from "unkown"; +type T = number; +new Foo(); + +// @Filename: /callAny.ts +declare var g: any; +type U = number; +g(); +g(); // Should get error for type argument + +// @Filename: /super.ts +import { A, B } from "unknown"; + +type T = number; + +export class C extends A { + m() { + super.m(1); + super.m(); // Should get error for type argument + } +} diff --git a/tests/cases/conformance/controlFlow/typeGuardsAsAssertions.ts b/tests/cases/conformance/controlFlow/typeGuardsAsAssertions.ts index 912eaa64e80..5ce430bc19a 100644 --- a/tests/cases/conformance/controlFlow/typeGuardsAsAssertions.ts +++ b/tests/cases/conformance/controlFlow/typeGuardsAsAssertions.ts @@ -120,3 +120,8 @@ function f6() { x = ""; x!.slice(); } + +function f7() { + let x: string; + x!.slice(); +} diff --git a/tests/cases/conformance/enums/enumBasics.ts b/tests/cases/conformance/enums/enumBasics.ts index 1e134540713..0a0f9d920cb 100644 --- a/tests/cases/conformance/enums/enumBasics.ts +++ b/tests/cases/conformance/enums/enumBasics.ts @@ -11,9 +11,9 @@ var x: number = E1.A; // Enum object type is anonymous with properties of the enum type and numeric indexer var e = E1; var e: { - readonly A: E1; - readonly B: E1; - readonly C: E1; + readonly A: E1.A; + readonly B: E1.B; + readonly C: E1.C; readonly [n: number]: string; }; var e: typeof E1; diff --git a/tests/cases/conformance/enums/enumClassification.ts b/tests/cases/conformance/enums/enumClassification.ts new file mode 100644 index 00000000000..bbb05984088 --- /dev/null +++ b/tests/cases/conformance/enums/enumClassification.ts @@ -0,0 +1,80 @@ +// @declaration: true + +// An enum type where each member has no initializer or an initializer that specififes +// a numeric literal, a string literal, or a single identifier naming another member in +// the enum type is classified as a literal enum type. An enum type that doesn't adhere +// to this pattern is classified as a numeric enum type. + +// Examples of literal enum types + +enum E01 { + A +} + +enum E02 { + A = 123 +} + +enum E03 { + A = "hello" +} + +enum E04 { + A, + B, + C +} + +enum E05 { + A, + B = 10, + C +} + +enum E06 { + A = "one", + B = "two", + C = "three" +} + +enum E07 { + A, + B, + C = "hi", + D = 10, + E, + F = "bye" +} + +enum E08 { + A = 10, + B = "hello", + C = A, + D = B, + E = C, +} + +// Examples of numeric enum types with only constant members + +enum E10 {} + +enum E11 { + A = +0, + B, + C +} + +enum E12 { + A = 1 << 0, + B = 1 << 1, + C = 1 << 2 +} + +// Examples of numeric enum types with constant and computed members + +enum E20 { + A = "foo".length, + B = A + 1, + C = +"123", + D = Math.sin(1) +} diff --git a/tests/cases/conformance/enums/enumErrors.ts b/tests/cases/conformance/enums/enumErrors.ts index ed438bb3ed6..99de3d4bc0d 100644 --- a/tests/cases/conformance/enums/enumErrors.ts +++ b/tests/cases/conformance/enums/enumErrors.ts @@ -23,8 +23,17 @@ enum E10 { // Enum with computed member intializer of other types enum E11 { - A = '', + A = true, B = new Date(), C = window, D = {} } + +// Enum with string valued member and computed member initializers +enum E12 { + A = '', + B = new Date(), + C = window, + D = {}, + E = 1 + 1, +} diff --git a/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts b/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts new file mode 100644 index 00000000000..9151f52f00d --- /dev/null +++ b/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts @@ -0,0 +1,38 @@ +declare function all(a?: number, b?: number): void; +declare function weird(a?: number | string, b?: number | string): void; +declare function prefix(s: string, a?: number, b?: number): void; +declare function rest(s: string, a?: number, b?: number, ...rest: number[]): void; +declare function normal(s: string): void; +declare function thunk(): string; + +declare var ns: number[]; +declare var mixed: (number | string)[]; +declare var tuple: [number, string]; + +// good +all(...ns) +weird(...ns) +weird(...mixed) +weird(...tuple) +prefix("a", ...ns) +rest("d", ...ns) + + +// this covers the arguments case +normal("g", ...ns) +normal("h", ...mixed) +normal("i", ...tuple) +thunk(...ns) +thunk(...mixed) +thunk(...tuple) + +// bad +all(...mixed) +all(...tuple) +prefix("b", ...mixed) +prefix("c", ...tuple) +rest("e", ...mixed) +rest("f", ...tuple) +prefix(...ns) // required parameters are required +prefix(...mixed) +prefix(...tuple) diff --git a/tests/cases/conformance/jsx/checkJsxChildrenProperty12.tsx b/tests/cases/conformance/jsx/checkJsxChildrenProperty12.tsx new file mode 100644 index 00000000000..e49b196b8f8 --- /dev/null +++ b/tests/cases/conformance/jsx/checkJsxChildrenProperty12.tsx @@ -0,0 +1,36 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +interface ButtonProp { + a: number, + b: string, + children: Button; +} + +class Button extends React.Component { + render() { + let condition: boolean; + if (condition) { + return + } + else { + return ( +

Hello World
+ ); + } + } +} + +interface InnerButtonProp { + a: number +} + +class InnerButton extends React.Component { + render() { + return (); + } +} diff --git a/tests/cases/conformance/jsx/checkJsxChildrenProperty13.tsx b/tests/cases/conformance/jsx/checkJsxChildrenProperty13.tsx new file mode 100644 index 00000000000..1584bf43159 --- /dev/null +++ b/tests/cases/conformance/jsx/checkJsxChildrenProperty13.tsx @@ -0,0 +1,31 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +interface ButtonProp { + a: number, + b: string, + children: Button; +} + +class Button extends React.Component { + render() { + // Error children are specified twice + return ( +
Hello World
+
); + } +} + +interface InnerButtonProp { + a: number +} + +class InnerButton extends React.Component { + render() { + return (); + } +} diff --git a/tests/cases/conformance/jsx/commentEmittingInPreserveJsx1.tsx b/tests/cases/conformance/jsx/commentEmittingInPreserveJsx1.tsx new file mode 100644 index 00000000000..323cd029189 --- /dev/null +++ b/tests/cases/conformance/jsx/commentEmittingInPreserveJsx1.tsx @@ -0,0 +1,35 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +
+ // Not Comment +
; + +
+ // Not Comment + { + //Comment just Fine + } + // Another not Comment +
; + +
+ // Not Comment + { + //Comment just Fine + "Hi" + } + // Another not Comment +
; + +
+ /* Not Comment */ + { + //Comment just Fine + "Hi" + } +
; \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxAttributeResolution3.tsx b/tests/cases/conformance/jsx/tsxAttributeResolution3.tsx index 0f968dd0a5c..d63cf8e4acc 100644 --- a/tests/cases/conformance/jsx/tsxAttributeResolution3.tsx +++ b/tests/cases/conformance/jsx/tsxAttributeResolution3.tsx @@ -32,7 +32,7 @@ var obj4 = { x: 32, y: 32 }; var obj5 = { x: 32, y: 32 }; -// Error +// Ok var obj6 = { x: 'ok', y: 32, extra: 100 }; diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType1.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType1.tsx new file mode 100644 index 00000000000..e6b7fc18ef7 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType1.tsx @@ -0,0 +1,18 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +const decorator = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; + +const decorator2 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; + +const decorator3 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType2.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType2.tsx new file mode 100644 index 00000000000..48acd55546f --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType2.tsx @@ -0,0 +1,10 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +const decorator4 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType3.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType3.tsx new file mode 100644 index 00000000000..b683c5e7970 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType3.tsx @@ -0,0 +1,17 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + render() { + return ; + } +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType4.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType4.tsx new file mode 100644 index 00000000000..b207f2b4398 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType4.tsx @@ -0,0 +1,18 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + render() { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + } +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType5.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType5.tsx new file mode 100644 index 00000000000..d0215da7397 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType5.tsx @@ -0,0 +1,19 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + props: U; + render() { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + } +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType6.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType6.tsx new file mode 100644 index 00000000000..d70df8a0cf7 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType6.tsx @@ -0,0 +1,18 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + props: U; + render() { + return ; + } +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType7.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType7.tsx new file mode 100644 index 00000000000..3044fda23df --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType7.tsx @@ -0,0 +1,15 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +declare function Component(props: T) : JSX.Element; +const decorator = function (props: U) { + return ; +} + +const decorator1 = function (props: U) { + return ; +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType8.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType8.tsx new file mode 100644 index 00000000000..b1d3a7445c8 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType8.tsx @@ -0,0 +1,15 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +declare function Component(props: T) : JSX.Element; +const decorator = function (props: U) { + return ; +} + +const decorator1 = function (props: U) { + return ; +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType9.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType9.tsx new file mode 100644 index 00000000000..a9466a43983 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType9.tsx @@ -0,0 +1,16 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +export function makeP

(Ctor: React.ComponentClass

): React.ComponentClass

{ + return class extends React.PureComponent { + public render(): JSX.Element { + return ( + + ); + } + }; +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution12.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution12.tsx index b5150bd27ff..457a3f29810 100644 --- a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution12.tsx +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution12.tsx @@ -32,3 +32,5 @@ let anyobj: any; let x = let x1 = let x2 = +let x3 = + diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution13.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution13.tsx new file mode 100644 index 00000000000..b665654514c --- /dev/null +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution13.tsx @@ -0,0 +1,33 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + let condition1: boolean; + if (condition1) { + return ( + + ); + } + else { + return (); + } +} + +interface AnotherComponentProps { + property1: string; +} + +function ChildComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution14.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution14.tsx new file mode 100644 index 00000000000..b9edcc8ab75 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution14.tsx @@ -0,0 +1,28 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + // Error extra property + + ); +} + +interface AnotherComponentProps { + property1: string; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution15.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution15.tsx new file mode 100644 index 00000000000..5ede01c0eab --- /dev/null +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution15.tsx @@ -0,0 +1,29 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + + ); +} + +interface AnotherComponentProps { + property1: string; + AnotherProperty1: string; + property2: boolean; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution16.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution16.tsx new file mode 100644 index 00000000000..98616661857 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution16.tsx @@ -0,0 +1,30 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + // Error: missing property + + ); +} + +interface AnotherComponentProps { + property1: string; + AnotherProperty1: string; + property2: boolean; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx index 1d647226ade..7ec1d871189 100644 --- a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx @@ -21,4 +21,6 @@ const obj = {}; // Error let p = ; let y = ; -let z = ; \ No newline at end of file +let z = ; +let w = ; +let w1 = ; \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution5.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution5.tsx index e050932b1db..22045c81451 100644 --- a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution5.tsx +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution5.tsx @@ -34,5 +34,5 @@ class EmptyProp extends React.Component<{}, {}> { let o = { prop1: false } -// Error +// Ok let e = ; \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxStatelessFunctionComponentOverload4.tsx b/tests/cases/conformance/jsx/tsxStatelessFunctionComponentOverload4.tsx index 7700fed6902..b96073b4cc0 100644 --- a/tests/cases/conformance/jsx/tsxStatelessFunctionComponentOverload4.tsx +++ b/tests/cases/conformance/jsx/tsxStatelessFunctionComponentOverload4.tsx @@ -18,7 +18,7 @@ let obj2: any; const c0 = ; // extra property; const c1 = ; // missing property; const c2 = ; // type incompatible; -const c3 = ; // Extra attribute; +const c3 = ; // This is OK becuase all attribute are spread const c4 = ; // extra property; const c5 = ; // type incompatible; const c6 = ; // Should error as there is extra attribute that doesn't match any. Current it is not diff --git a/tests/cases/conformance/jsx/tsxStatelessFunctionComponents1.tsx b/tests/cases/conformance/jsx/tsxStatelessFunctionComponents1.tsx index 8990cb3c8b0..b486a72ce15 100644 --- a/tests/cases/conformance/jsx/tsxStatelessFunctionComponents1.tsx +++ b/tests/cases/conformance/jsx/tsxStatelessFunctionComponents1.tsx @@ -46,7 +46,7 @@ let o = { prop1: true; } -// Error +// OK as access properties are allow when spread let i2 = let o1: any; diff --git a/tests/cases/conformance/jsx/tsxStatelessFunctionComponentsWithTypeArguments5.tsx b/tests/cases/conformance/jsx/tsxStatelessFunctionComponentsWithTypeArguments5.tsx index 527eb689ddb..c19bfdf43bd 100644 --- a/tests/cases/conformance/jsx/tsxStatelessFunctionComponentsWithTypeArguments5.tsx +++ b/tests/cases/conformance/jsx/tsxStatelessFunctionComponentsWithTypeArguments5.tsx @@ -6,7 +6,6 @@ import React = require('react') -// Error, can only spread object type declare function Component(l: U): JSX.Element; function createComponent(arg: T) { let a1 = ; @@ -16,9 +15,9 @@ function createComponent(arg: T) { declare function ComponentSpecific(l: { prop: U }): JSX.Element; declare function ComponentSpecific1(l: { prop: U, "ignore-prop": number }): JSX.Element; -// Error, can only spread object type function Bar(arg: T) { let a1 = ; // U is number let a2 = ; // U is number let a3 = ; // U is "hello" + let a4 = ; // U is "hello" } diff --git a/tests/cases/conformance/salsa/jsDocTypes2.ts b/tests/cases/conformance/salsa/jsDocTypes2.ts new file mode 100644 index 00000000000..612804b91d7 --- /dev/null +++ b/tests/cases/conformance/salsa/jsDocTypes2.ts @@ -0,0 +1,23 @@ +// @allowJS: true +// @suppressOutputPathCheck: true + +// @filename: 0.js +// @ts-check +/** @type {*} */ +var anyT = 2; + +/** @type {?} */ +var anyT1 = 2; +anyT1 = "hi"; + +/** @type {Function} */ +const x = (a) => a + 1; +x(1); + +/** @type {function (number)} */ +const x1 = (a) => a + 1; +x1(0); + +/** @type {function (number): number} */ +const x2 = (a) => a + 1; +x2(0); \ No newline at end of file diff --git a/tests/cases/conformance/salsa/jsDocTypes3.ts b/tests/cases/conformance/salsa/jsDocTypes3.ts new file mode 100644 index 00000000000..bf207bca869 --- /dev/null +++ b/tests/cases/conformance/salsa/jsDocTypes3.ts @@ -0,0 +1,16 @@ +// @allowJS: true +// @suppressOutputPathCheck: true + +// @filename: 0.js +// @ts-check + +/** @type {function (number)} */ +const x1 = (a) => a + 1; +x1("string"); + +/** @type {function (number): number} */ +const x2 = (a) => a + 1; + +/** @type {string} */ +var a; +a = x2(0); \ No newline at end of file diff --git a/tests/cases/conformance/types/literal/stringEnumLiteralTypes1.ts b/tests/cases/conformance/types/literal/stringEnumLiteralTypes1.ts new file mode 100644 index 00000000000..11be7c90603 --- /dev/null +++ b/tests/cases/conformance/types/literal/stringEnumLiteralTypes1.ts @@ -0,0 +1,99 @@ +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + +type YesNo = Choice.Yes | Choice.No; +type NoYes = Choice.No | Choice.Yes; +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + +function f1() { + var a: YesNo; + var a: NoYes; + var a: Choice.Yes | Choice.No; + var a: Choice.No | Choice.Yes; +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { + b = a; + c = a; + c = b; +} + +function f3(a: Choice.Yes, b: YesNo) { + var x = a + b; + var y = a == b; + var y = a != b; + var y = a === b; + var y = a !== b; + var y = a > b; + var y = a < b; + var y = a >= b; + var y = a <= b; + var y = !b; +} + +declare function g(x: Choice.Yes): string; +declare function g(x: Choice.No): boolean; +declare function g(x: Choice): number; + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { + var z1 = g(Choice.Yes); + var z2 = g(Choice.No); + var z3 = g(a); + var z4 = g(b); + var z5 = g(c); +} + +function assertNever(x: never): never { + throw new Error("Unexpected value"); +} + +function f10(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } +} + +function f11(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } + return assertNever(x); +} + +function f12(x: UnknownYesNo) { + if (x) { + x; + } + else { + x; + } +} + +function f13(x: UnknownYesNo) { + if (x === Choice.Yes) { + x; + } + else { + x; + } +} + +type Item = + { kind: Choice.Yes, a: string } | + { kind: Choice.No, b: string }; + +function f20(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } +} + +function f21(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } + return assertNever(x); +} \ No newline at end of file diff --git a/tests/cases/conformance/types/literal/stringEnumLiteralTypes2.ts b/tests/cases/conformance/types/literal/stringEnumLiteralTypes2.ts new file mode 100644 index 00000000000..f6a71fcaa74 --- /dev/null +++ b/tests/cases/conformance/types/literal/stringEnumLiteralTypes2.ts @@ -0,0 +1,101 @@ +// @strictNullChecks: true + +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + +type YesNo = Choice.Yes | Choice.No; +type NoYes = Choice.No | Choice.Yes; +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + +function f1() { + var a: YesNo; + var a: NoYes; + var a: Choice.Yes | Choice.No; + var a: Choice.No | Choice.Yes; +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { + b = a; + c = a; + c = b; +} + +function f3(a: Choice.Yes, b: YesNo) { + var x = a + b; + var y = a == b; + var y = a != b; + var y = a === b; + var y = a !== b; + var y = a > b; + var y = a < b; + var y = a >= b; + var y = a <= b; + var y = !b; +} + +declare function g(x: Choice.Yes): string; +declare function g(x: Choice.No): boolean; +declare function g(x: Choice): number; + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { + var z1 = g(Choice.Yes); + var z2 = g(Choice.No); + var z3 = g(a); + var z4 = g(b); + var z5 = g(c); +} + +function assertNever(x: never): never { + throw new Error("Unexpected value"); +} + +function f10(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } +} + +function f11(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } + return assertNever(x); +} + +function f12(x: UnknownYesNo) { + if (x) { + x; + } + else { + x; + } +} + +function f13(x: UnknownYesNo) { + if (x === Choice.Yes) { + x; + } + else { + x; + } +} + +type Item = + { kind: Choice.Yes, a: string } | + { kind: Choice.No, b: string }; + +function f20(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } +} + +function f21(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } + return assertNever(x); +} \ No newline at end of file diff --git a/tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts b/tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts new file mode 100644 index 00000000000..f296fd875f6 --- /dev/null +++ b/tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts @@ -0,0 +1,119 @@ +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + +type Yes = Choice.Yes; +type YesNo = Choice.Yes | Choice.No; +type NoYes = Choice.No | Choice.Yes; +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + +function f1(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a = a; + a = b; + a = c; + a = d; +} + +function f2(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + b = a; + b = b; + b = c; + b = d; +} + +function f3(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + c = a; + c = b; + c = c; + c = d; +} + +function f4(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + d = a; + d = b; + d = c; + d = d; +} + +function f5(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a = Choice.Unknown; + a = Choice.Yes; + a = Choice.No; + b = Choice.Unknown; + b = Choice.Yes; + b = Choice.No; + c = Choice.Unknown; + c = Choice.Yes; + c = Choice.No; + d = Choice.Unknown; + d = Choice.Yes; + d = Choice.No; +} + +function f6(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a === Choice.Unknown; + a === Choice.Yes; + a === Choice.No; + b === Choice.Unknown; + b === Choice.Yes; + b === Choice.No; + c === Choice.Unknown; + c === Choice.Yes; + c === Choice.No; + d === Choice.Unknown; + d === Choice.Yes; + d === Choice.No; +} + +function f7(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a === a; + a === b; + a === c; + a === d; + b === a; + b === b; + b === c; + b === d; + c === a; + c === b; + c === c; + c === d; + d === a; + d === b; + d === c; + d === d; +} + +function f10(x: Yes): Yes { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +function f11(x: YesNo): YesNo { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +function f12(x: UnknownYesNo): UnknownYesNo { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +function f13(x: Choice): Choice { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} \ No newline at end of file diff --git a/tests/cases/conformance/types/spread/objectSpreadStrictNull.ts b/tests/cases/conformance/types/spread/objectSpreadStrictNull.ts index 087d47df26c..979a6feed03 100644 --- a/tests/cases/conformance/types/spread/objectSpreadStrictNull.ts +++ b/tests/cases/conformance/types/spread/objectSpreadStrictNull.ts @@ -19,3 +19,12 @@ function f( let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; } + +type Movie = { + title: string; + yearReleased: number; +} + +const m = { title: "The Matrix", yearReleased: 1999 }; +// should error here because title: undefined is not assignable to string +const x: Movie = { ...m, title: undefined }; diff --git a/tests/cases/fourslash/ambientShorthandGotoDefinition.ts b/tests/cases/fourslash/ambientShorthandGotoDefinition.ts index 410fc932cec..74e348beb74 100644 --- a/tests/cases/fourslash/ambientShorthandGotoDefinition.ts +++ b/tests/cases/fourslash/ambientShorthandGotoDefinition.ts @@ -12,7 +12,7 @@ verify.quickInfoAt("useFoo", "import foo"); verify.goToDefinition({ - useFoo: "importFoo", + useFoo: "module", importFoo: "module" }); @@ -27,6 +27,6 @@ verify.goToDefinition({ verify.quickInfoAt("useBang", "import bang = require(\"jquery\")"); verify.goToDefinition({ - useBang: "importBang", + useBang: "module", importBang: "module" }); diff --git a/tests/cases/fourslash/codeFixAddMissingMember3.ts b/tests/cases/fourslash/codeFixAddMissingMember3.ts index 5864c9c1029..47cacd6753a 100644 --- a/tests/cases/fourslash/codeFixAddMissingMember3.ts +++ b/tests/cases/fourslash/codeFixAddMissingMember3.ts @@ -11,4 +11,4 @@ verify.rangeAfterCodeFix(`class C { static method() { this.foo = 10; } -}`); \ No newline at end of file +}`, /*includeWhiteSpace*/false, /*errorCode*/ undefined, /*index*/ 0); diff --git a/tests/cases/fourslash/codeFixClassImplementInterfaceIndexSignaturesString.ts b/tests/cases/fourslash/codeFixClassImplementInterfaceIndexSignaturesString.ts index 4b595c6eda7..9d42faada36 100644 --- a/tests/cases/fourslash/codeFixClassImplementInterfaceIndexSignaturesString.ts +++ b/tests/cases/fourslash/codeFixClassImplementInterfaceIndexSignaturesString.ts @@ -1,11 +1,11 @@ /// //// interface I { -//// [x: string]: X; +//// [Ƚ: string]: X; //// } //// //// class C implements I {[| |]} verify.rangeAfterCodeFix(` - [x: string]: number; + [Ƚ: string]: number; `); \ No newline at end of file diff --git a/tests/cases/fourslash/codeFixClassImplementInterfaceInheritsAbstractMethod.ts b/tests/cases/fourslash/codeFixClassImplementInterfaceInheritsAbstractMethod.ts index c141592823a..7bb230a2dfb 100644 --- a/tests/cases/fourslash/codeFixClassImplementInterfaceInheritsAbstractMethod.ts +++ b/tests/cases/fourslash/codeFixClassImplementInterfaceInheritsAbstractMethod.ts @@ -2,12 +2,12 @@ //// abstract class C1 { } //// abstract class C2 { -//// abstract f1(); +//// abstract fA(); //// } //// interface I1 extends C1, C2 { } //// class C3 implements I1 {[| |]} -verify.rangeAfterCodeFix(`f1(){ +verify.rangeAfterCodeFix(`fA(){ throw new Error("Method not implemented."); } `); \ No newline at end of file diff --git a/tests/cases/fourslash/codeFixClassImplementInterfaceMemberNestedTypeAlias.ts b/tests/cases/fourslash/codeFixClassImplementInterfaceMemberNestedTypeAlias.ts new file mode 100644 index 00000000000..5aa5f1a4e51 --- /dev/null +++ b/tests/cases/fourslash/codeFixClassImplementInterfaceMemberNestedTypeAlias.ts @@ -0,0 +1,16 @@ +/// + +//// type Either = { val: T } | Error; +//// interface I { +//// x: Either>; +//// foo(x: Either>): void; +//// } +//// class C implements I {[| |]} + +verify.rangeAfterCodeFix(` + x: Either>; + foo(x: Either>): void { + throw new Error("Method not implemented."); + } +`); + diff --git a/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts b/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts new file mode 100644 index 00000000000..44981302a1a --- /dev/null +++ b/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts @@ -0,0 +1,12 @@ +/// + +//// type MyType = [string, number]; +//// interface I { x: MyType; test(a: MyType): void; } +//// class C implements I {[| |]} + +verify.rangeAfterCodeFix(` + x: [string, number]; + test(a: [string, number]): void { + throw new Error("Method not implemented."); + } +`); diff --git a/tests/cases/fourslash/codeFixClassImplementInterfaceMultipleImplements2.ts b/tests/cases/fourslash/codeFixClassImplementInterfaceMultipleImplements2.ts index e5100b88f6c..946b6495c5f 100644 --- a/tests/cases/fourslash/codeFixClassImplementInterfaceMultipleImplements2.ts +++ b/tests/cases/fourslash/codeFixClassImplementInterfaceMultipleImplements2.ts @@ -4,7 +4,7 @@ //// x: number; //// } //// interface I2 { -//// y: number; +//// y: "𣋝ઢȴ¬⏊"; //// } //// //// class C implements I1,I2 {[| @@ -12,7 +12,7 @@ //// } verify.rangeAfterCodeFix(` -y: number; +y: "𣋝ઢȴ¬⏊"; `); verify.not.codeFixAvailable(); diff --git a/tests/cases/fourslash/completionEntryForClassMembers.ts b/tests/cases/fourslash/completionEntryForClassMembers.ts new file mode 100644 index 00000000000..527611b85bf --- /dev/null +++ b/tests/cases/fourslash/completionEntryForClassMembers.ts @@ -0,0 +1,256 @@ +/// + +////abstract class B { +//// private privateMethod() { } +//// protected protectedMethod() { }; +//// static staticMethod() { } +//// abstract getValue(): number; +//// /*abstractClass*/ +////} +////class C extends B { +//// /*classThatIsEmptyAndExtendingAnotherClass*/ +////} +////class D extends B { +//// /*classThatHasAlreadyImplementedAnotherClassMethod*/ +//// getValue() { +//// return 10; +//// } +//// /*classThatHasAlreadyImplementedAnotherClassMethodAfterMethod*/ +////} +////class D1 extends B { +//// /*classThatHasDifferentMethodThanBase*/ +//// getValue1() { +//// return 10; +//// } +//// /*classThatHasDifferentMethodThanBaseAfterMethod*/ +////} +////class D2 extends B { +//// /*classThatHasAlreadyImplementedAnotherClassProtectedMethod*/ +//// protectedMethod() { +//// } +//// /*classThatHasDifferentMethodThanBaseAfterProtectedMethod*/ +////} +////class D3 extends D1 { +//// /*classThatExtendsClassExtendingAnotherClass*/ +////} +////class D4 extends D1 { +//// static /*classThatExtendsClassExtendingAnotherClassAndTypesStatic*/ +////} +////class D5 extends D2 { +//// /*classThatExtendsClassExtendingAnotherClassWithOverridingMember*/ +////} +////class D6 extends D2 { +//// static /*classThatExtendsClassExtendingAnotherClassWithOverridingMemberAndTypesStatic*/ +////} +////class E { +//// /*classThatDoesNotExtendAnotherClass*/ +////} +////class F extends B { +//// public /*classThatHasWrittenPublicKeyword*/ +////} +////class F2 extends B { +//// private /*classThatHasWrittenPrivateKeyword*/ +////} +////class G extends B { +//// static /*classElementContainingStatic*/ +////} +////class G2 extends B { +//// private static /*classElementContainingPrivateStatic*/ +////} +////class H extends B { +//// prop/*classThatStartedWritingIdentifier*/ +////} +//////Class for location verification +////class I extends B { +//// prop0: number +//// /*propDeclarationWithoutSemicolon*/ +//// prop: number; +//// /*propDeclarationWithSemicolon*/ +//// prop1 = 10; +//// /*propAssignmentWithSemicolon*/ +//// prop2 = 10 +//// /*propAssignmentWithoutSemicolon*/ +//// method(): number +//// /*methodSignatureWithoutSemicolon*/ +//// method2(): number; +//// /*methodSignatureWithSemicolon*/ +//// method3() { +//// /*InsideMethod*/ +//// } +//// /*methodImplementation*/ +//// get c() +//// /*accessorSignatureWithoutSemicolon*/ +//// set c() +//// { +//// } +//// /*accessorSignatureImplementation*/ +////} +////class J extends B { +//// get /*classThatHasWrittenGetKeyword*/ +////} +////class K extends B { +//// set /*classThatHasWrittenSetKeyword*/ +////} +////class J extends B { +//// get identi/*classThatStartedWritingIdentifierOfGetAccessor*/ +////} +////class K extends B { +//// set identi/*classThatStartedWritingIdentifierOfSetAccessor*/ +////} +////class L extends B { +//// public identi/*classThatStartedWritingIdentifierAfterModifier*/ +////} +////class L2 extends B { +//// private identi/*classThatStartedWritingIdentifierAfterPrivateModifier*/ +////} +////class M extends B { +//// static identi/*classThatStartedWritingIdentifierAfterStaticModifier*/ +////} +////class M extends B { +//// private static identi/*classThatStartedWritingIdentifierAfterPrivateStaticModifier*/ +////} +////class N extends B { +//// async /*classThatHasWrittenAsyncKeyword*/ +////} + +const allowedKeywordCount = verify.allowedClassElementKeywords.length; +type CompletionInfo = [string, string]; +type CompletionInfoVerifier = { validMembers: CompletionInfo[], invalidMembers: CompletionInfo[] }; + +function verifyClassElementLocations({ validMembers, invalidMembers }: CompletionInfoVerifier, classElementCompletionLocations: string[]) { + for (const marker of classElementCompletionLocations) { + goTo.marker(marker); + verifyCompletionInfo(validMembers, verify); + verifyCompletionInfo(invalidMembers, verify.not); + verify.completionListContainsClassElementKeywords(); + verify.completionListCount(allowedKeywordCount + validMembers.length); + } +} + +function verifyCompletionInfo(memberInfo: CompletionInfo[], verify: FourSlashInterface.verifyNegatable) { + for (const [symbol, text] of memberInfo) { + verify.completionListContains(symbol, text, /*documentation*/ undefined, "method"); + } +} + +const allMembersOfBase: CompletionInfo[] = [ + ["getValue", "(method) B.getValue(): number"], + ["protectedMethod", "(method) B.protectedMethod(): void"], + ["privateMethod", "(method) B.privateMethod(): void"], + ["staticMethod", "(method) B.staticMethod(): void"] +]; +const publicCompletionInfoOfD1: CompletionInfo[] = [ + ["getValue1", "(method) D1.getValue1(): number"] +]; +const publicCompletionInfoOfD2: CompletionInfo[] = [ + ["protectedMethod", "(method) D2.protectedMethod(): void"] +]; +function filterCompletionInfo(fn: (a: CompletionInfo) => boolean): CompletionInfoVerifier { + const validMembers: CompletionInfo[] = []; + const invalidMembers: CompletionInfo[] = []; + for (const member of allMembersOfBase) { + if (fn(member)) { + validMembers.push(member); + } + else { + invalidMembers.push(member); + } + } + return { validMembers, invalidMembers }; +} + + +const instanceMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "getValue" || a === "protectedMethod"); +const staticMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "staticMethod"); +const instanceWithoutProtectedMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "getValue"); +const instanceWithoutPublicMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "protectedMethod"); + +const instanceMemberInfoD1: CompletionInfoVerifier = { + validMembers: instanceMemberInfo.validMembers.concat(publicCompletionInfoOfD1), + invalidMembers: instanceMemberInfo.invalidMembers +}; +const instanceMemberInfoD2: CompletionInfoVerifier = { + validMembers: instanceWithoutProtectedMemberInfo.validMembers.concat(publicCompletionInfoOfD2), + invalidMembers: instanceWithoutProtectedMemberInfo.invalidMembers +}; +const staticMemberInfoDn: CompletionInfoVerifier = { + validMembers: staticMemberInfo.validMembers, + invalidMembers: staticMemberInfo.invalidMembers.concat(publicCompletionInfoOfD1, publicCompletionInfoOfD2) +}; + +// Not a class element declaration location +const nonClassElementMarkers = [ + "InsideMethod" +]; +for (const marker of nonClassElementMarkers) { + goTo.marker(marker); + verifyCompletionInfo(allMembersOfBase, verify.not); + verify.not.completionListIsEmpty(); +} + +// Only keywords allowed at this position since they dont extend the class or are private +const onlyClassElementKeywordLocations = [ + "abstractClass", + "classThatDoesNotExtendAnotherClass", + "classThatHasWrittenPrivateKeyword", + "classElementContainingPrivateStatic", + "classThatStartedWritingIdentifierAfterPrivateModifier", + "classThatStartedWritingIdentifierAfterPrivateStaticModifier" +]; +verifyClassElementLocations({ validMembers: [], invalidMembers: allMembersOfBase }, onlyClassElementKeywordLocations); + +// Instance base members and class member keywords allowed +const classInstanceElementLocations = [ + "classThatIsEmptyAndExtendingAnotherClass", + "classThatHasDifferentMethodThanBase", + "classThatHasDifferentMethodThanBaseAfterMethod", + "classThatHasWrittenPublicKeyword", + "classThatStartedWritingIdentifier", + "propDeclarationWithoutSemicolon", + "propDeclarationWithSemicolon", + "propAssignmentWithSemicolon", + "propAssignmentWithoutSemicolon", + "methodSignatureWithoutSemicolon", + "methodSignatureWithSemicolon", + "methodImplementation", + "accessorSignatureWithoutSemicolon", + "accessorSignatureImplementation", + "classThatHasWrittenGetKeyword", + "classThatHasWrittenSetKeyword", + "classThatStartedWritingIdentifierOfGetAccessor", + "classThatStartedWritingIdentifierOfSetAccessor", + "classThatStartedWritingIdentifierAfterModifier", + "classThatHasWrittenAsyncKeyword" +]; +verifyClassElementLocations(instanceMemberInfo, classInstanceElementLocations); + +// Static Base members and class member keywords allowed +const staticClassLocations = [ + "classElementContainingStatic", + "classThatStartedWritingIdentifierAfterStaticModifier" +]; +verifyClassElementLocations(staticMemberInfo, staticClassLocations); + +const classInstanceElementWithoutPublicMethodLocations = [ + "classThatHasAlreadyImplementedAnotherClassMethod", + "classThatHasAlreadyImplementedAnotherClassMethodAfterMethod", +]; +verifyClassElementLocations(instanceWithoutPublicMemberInfo, classInstanceElementWithoutPublicMethodLocations); + +const classInstanceElementWithoutProtectedMethodLocations = [ + "classThatHasAlreadyImplementedAnotherClassProtectedMethod", + "classThatHasDifferentMethodThanBaseAfterProtectedMethod", +]; +verifyClassElementLocations(instanceWithoutProtectedMemberInfo, classInstanceElementWithoutProtectedMethodLocations); + +// instance memebers in D1 and base class are shown +verifyClassElementLocations(instanceMemberInfoD1, ["classThatExtendsClassExtendingAnotherClass"]); + +// instance memebers in D2 and base class are shown +verifyClassElementLocations(instanceMemberInfoD2, ["classThatExtendsClassExtendingAnotherClassWithOverridingMember"]); + +// static base members and class member keywords allowed +verifyClassElementLocations(staticMemberInfoDn, [ + "classThatExtendsClassExtendingAnotherClassAndTypesStatic", + "classThatExtendsClassExtendingAnotherClassWithOverridingMemberAndTypesStatic" +]); \ No newline at end of file diff --git a/tests/cases/fourslash/completionEntryForClassMembers2.ts b/tests/cases/fourslash/completionEntryForClassMembers2.ts new file mode 100644 index 00000000000..539702196a3 --- /dev/null +++ b/tests/cases/fourslash/completionEntryForClassMembers2.ts @@ -0,0 +1,456 @@ +/// + +////interface I { +//// methodOfInterface(): number; +////} +////interface I2 { +//// methodOfInterface2(): number; +////} +////interface I3 { +//// getValue(): string; +//// method(): string; +////} +////interface I4 { +//// staticMethod(): void; +//// method(): string; +////} +////class B0 { +//// private privateMethod() { } +//// protected protectedMethod() { } +//// static staticMethod() { } +//// getValue(): string | boolean { return "hello"; } +//// private privateMethod1() { } +//// protected protectedMethod1() { } +//// static staticMethod1() { } +//// getValue1(): string | boolean { return "hello"; } +////} +////interface I5 extends B0 { +//// methodOfInterface5(): number; +////} +////interface I6 extends B0 { +//// methodOfInterface6(): number; +//// staticMethod(): void; +////} +////interface I7 extends I { +//// methodOfInterface7(): number; +////} +////class B { +//// private privateMethod() { } +//// protected protectedMethod() { } +//// static staticMethod() { } +//// getValue(): string | boolean { return "hello"; } +////} +////class C0 implements I, I2 { +//// /*implementsIAndI2*/ +////} +////class C00 implements I, I2 { +//// static /*implementsIAndI2AndWritingStatic*/ +////} +////class C001 implements I, I2 { +//// methodOfInterface/*implementsIAndI2AndWritingMethodNameOfI*/ +////} +////class C extends B implements I, I2 { +//// /*extendsBAndImplementsIAndI2*/ +////} +////class C1 extends B implements I, I2 { +//// static /*extendsBAndImplementsIAndI2AndWritingStatic*/ +////} +////class D extends B implements I, I2 { +//// /*extendsBAndImplementsIAndI2WithMethodFromB*/ +//// protected protectedMethod() { +//// return "protected"; +//// } +////} +////class E extends B implements I, I2 { +//// /*extendsBAndImplementsIAndI2WithMethodFromI*/ +//// methodOfInterface() { +//// return 1; +//// } +////} +////class F extends B implements I, I2 { +//// /*extendsBAndImplementsIAndI2WithMethodFromBAndI*/ +//// protected protectedMethod() { +//// return "protected" +//// } +//// methodOfInterface() { +//// return 1; +//// } +////} +////class F2 extends B implements I, I2 { +//// protected protectedMethod() { +//// return "protected" +//// } +//// methodOfInterface() { +//// return 1; +//// } +//// static /*extendsBAndImplementsIAndI2WithMethodFromBAndIAndTypesStatic*/ +////} +////class G extends B implements I3 { +//// /*extendsBAndImplementsI3WithSameNameMembers*/ +////} +////class H extends B implements I3 { +//// /*extendsBAndImplementsI3WithSameNameMembersAndHasImplementedTheMember*/ +//// getValue() { +//// return "hello"; +//// } +////} +////class J extends B0 implements I4 { +//// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethod*/ +////} +////class L extends B0 implements I4 { +//// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethod*/ +//// staticMethod2() { +//// return "hello"; +//// } +////} +////class K extends B0 implements I4 { +//// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethod*/ +//// staticMethod() { +//// return "hello"; +//// } +////} +////class M extends B0 implements I4 { +//// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStatic*/ +//// static staticMethod() { +//// return "hello"; +//// } +////} +////class N extends B0 implements I4 { +//// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBoth*/ +//// staticMethod() { +//// return "hello"; +//// } +//// static staticMethod() { +//// return "hello"; +//// } +////} +////class J1 extends B0 implements I4 { +//// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodWritingStatic*/ +////} +////class L1 extends B0 implements I4 { +//// staticMethod2() { +//// return "hello"; +//// } +//// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethodWritingStatic*/ +////} +////class K1 extends B0 implements I4 { +//// staticMethod() { +//// return "hello"; +//// } +//// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodWritingStatic*/ +////} +////class M1 extends B0 implements I4 { +//// static staticMethod() { +//// return "hello"; +//// } +//// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStaticWritingStatic*/ +////} +////class N1 extends B0 implements I4 { +//// staticMethod() { +//// return "hello"; +//// } +//// static staticMethod() { +//// return "hello"; +//// } +//// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBothWritingStatic*/ +////} +////class O implements I7 { +//// /*implementsI7whichExtendsI*/ +////} +////class P implements I7, I { +//// /*implementsI7whichExtendsIAndAlsoImplementsI*/ +////} +////class Q implements I, I7 { +//// /*implementsIAndAlsoImplementsI7whichExtendsI*/ +////} +////class R implements I5 { +//// /*implementsI5ThatExtendsB0*/ +////} +////class S implements I6 { +//// /*implementsI6ThatExtendsB0AndHasStaticMethodOfB0*/ +////} +////class T extends B0 implements I5 { +//// /*extendsB0AndImplementsI5ThatExtendsB0*/ +////} +////class U extends B0 implements I6 { +//// /*extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0*/ +////} +////class R1 implements I5 { +//// static /*implementsI5ThatExtendsB0TypesStatic*/ +////} +////class S1 implements I6 { +//// static /*implementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic*/ +////} +////class T1 extends B0 implements I5 { +//// static /*extendsB0AndImplementsI5ThatExtendsB0TypesStatic*/ +////} +////class U1 extends B0 implements I6 { +//// static /*extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic*/ +////} + +const allowedKeywordCount = verify.allowedClassElementKeywords.length; +type CompletionInfo = [string, string]; +type CompletionInfoVerifier = { validMembers: CompletionInfo[], invalidMembers: CompletionInfo[] }; + +function verifyClassElementLocations({ validMembers, invalidMembers }: CompletionInfoVerifier, classElementCompletionLocations: string[]) { + for (const marker of classElementCompletionLocations) { + goTo.marker(marker); + verifyCompletionInfo(validMembers, verify); + verifyCompletionInfo(invalidMembers, verify.not); + verify.completionListContainsClassElementKeywords(); + verify.completionListCount(allowedKeywordCount + validMembers.length); + } +} + +function verifyCompletionInfo(memberInfo: CompletionInfo[], verify: FourSlashInterface.verifyNegatable) { + for (const [symbol, text] of memberInfo) { + verify.completionListContains(symbol, text, /*documentation*/ undefined, "method"); + } +} + +const validInstanceMembersOfBaseClassB: CompletionInfo[] = [ + ["getValue", "(method) B.getValue(): string | boolean"], + ["protectedMethod", "(method) B.protectedMethod(): void"], +]; +const validStaticMembersOfBaseClassB: CompletionInfo[] = [ + ["staticMethod", "(method) B.staticMethod(): void"] +]; +const privateMembersOfBaseClassB: CompletionInfo[] = [ + ["privateMethod", "(method) B.privateMethod(): void"], +]; +const protectedPropertiesOfBaseClassB0: CompletionInfo[] = [ + ["protectedMethod", "(method) B0.protectedMethod(): void"], + ["protectedMethod1", "(method) B0.protectedMethod1(): void"], +]; +const publicPropertiesOfBaseClassB0: CompletionInfo[] = [ + ["getValue", "(method) B0.getValue(): string | boolean"], + ["getValue1", "(method) B0.getValue1(): string | boolean"], +]; +const validInstanceMembersOfBaseClassB0: CompletionInfo[] = protectedPropertiesOfBaseClassB0.concat(publicPropertiesOfBaseClassB0); +const validStaticMembersOfBaseClassB0: CompletionInfo[] = [ + ["staticMethod", "(method) B0.staticMethod(): void"], + ["staticMethod1", "(method) B0.staticMethod1(): void"] +]; +const privateMembersOfBaseClassB0: CompletionInfo[] = [ + ["privateMethod", "(method) B0.privateMethod(): void"], + ["privateMethod1", "(method) B0.privateMethod1(): void"], +]; +const membersOfI: CompletionInfo[] = [ + ["methodOfInterface", "(method) I.methodOfInterface(): number"], +]; +const membersOfI2: CompletionInfo[] = [ + ["methodOfInterface2", "(method) I2.methodOfInterface2(): number"], +]; +const membersOfI3: CompletionInfo[] = [ + ["getValue", "(method) I3.getValue(): string"], + ["method", "(method) I3.method(): string"], +]; +const membersOfI4: CompletionInfo[] = [ + ["staticMethod", "(method) I4.staticMethod(): void"], + ["method", "(method) I4.method(): string"], +]; +const membersOfI5: CompletionInfo[] = publicPropertiesOfBaseClassB0.concat([ + ["methodOfInterface5", "(method) I5.methodOfInterface5(): number"] +]); +const membersOfI6: CompletionInfo[] = publicPropertiesOfBaseClassB0.concat([ + ["staticMethod", "(method) I6.staticMethod(): void"], + ["methodOfInterface6", "(method) I6.methodOfInterface6(): number"] +]); +const membersOfI7: CompletionInfo[] = membersOfI.concat([ + ["methodOfInterface7", "(method) I7.methodOfInterface7(): number"] +]); + +function getCompletionInfoVerifier( + validMembers: CompletionInfo[], + invalidMembers: CompletionInfo[], + arrayToDistribute: CompletionInfo[], + isValidDistributionCriteria: (v: CompletionInfo) => boolean): CompletionInfoVerifier { + if (arrayToDistribute) { + validMembers = validMembers.concat(arrayToDistribute.filter(isValidDistributionCriteria)); + invalidMembers = invalidMembers.concat(arrayToDistribute.filter(v => !isValidDistributionCriteria(v))); + } + return { + validMembers, + invalidMembers + } +} + +const noMembers: CompletionInfo[] = []; +const membersOfIAndI2 = membersOfI.concat(membersOfI2); +const invalidMembersOfBAtInstanceLocation = privateMembersOfBaseClassB.concat(validStaticMembersOfBaseClassB); + +// members of I and I2 +verifyClassElementLocations({ validMembers: membersOfIAndI2, invalidMembers: noMembers }, [ + "implementsIAndI2", + "implementsIAndI2AndWritingMethodNameOfI" +]); + +// Static location so no members of I and I2 +verifyClassElementLocations({ validMembers: noMembers, invalidMembers: membersOfIAndI2 }, + ["implementsIAndI2AndWritingStatic"]); + +const allInstanceBAndIAndI2 = membersOfIAndI2.concat(validInstanceMembersOfBaseClassB); +// members of instance B, I and I2 +verifyClassElementLocations({ + validMembers: allInstanceBAndIAndI2, + invalidMembers: invalidMembersOfBAtInstanceLocation +}, ["extendsBAndImplementsIAndI2"]); + +// static location so only static members of B and no members of instance B, I and I2 +verifyClassElementLocations({ + validMembers: validStaticMembersOfBaseClassB, + invalidMembers: privateMembersOfBaseClassB.concat(allInstanceBAndIAndI2) +}, [ + "extendsBAndImplementsIAndI2AndWritingStatic", + "extendsBAndImplementsIAndI2WithMethodFromBAndIAndTypesStatic" + ]); + +// instance members of B without protectedMethod, I and I2 +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ membersOfIAndI2, + /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, + /*arrayToDistribute*/ validInstanceMembersOfBaseClassB, + value => value[0] !== "protectedMethod"), + ["extendsBAndImplementsIAndI2WithMethodFromB"]); + +// instance members of B, members of T without methodOfInterface and I2 +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ membersOfI2.concat(validInstanceMembersOfBaseClassB), + /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, + /*arrayToDistribute*/ membersOfI, + value => value[0] !== "methodOfInterface"), + ["extendsBAndImplementsIAndI2WithMethodFromI"]); + +// instance members of B without protectedMethod, members of T without methodOfInterface and I2 +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ membersOfI2, + /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, + /*arrayToDistribute*/ membersOfI.concat(validInstanceMembersOfBaseClassB), + value => value[0] !== "methodOfInterface" && value[0] !== "protectedMethod"), + ["extendsBAndImplementsIAndI2WithMethodFromBAndI"]); + +// members of B and members of I3 that are not same as name of method in B +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ validInstanceMembersOfBaseClassB, + /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, + /*arrayToDistribute*/ membersOfI3, + value => value[0] !== "getValue"), + ["extendsBAndImplementsI3WithSameNameMembers"]); + +// members of B (without getValue since its implemented) and members of I3 that are not same as name of method in B +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ noMembers, + /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, + /*arrayToDistribute*/ membersOfI3.concat(validInstanceMembersOfBaseClassB), + value => value[0] !== "getValue"), + ["extendsBAndImplementsI3WithSameNameMembersAndHasImplementedTheMember"]); + +const invalidMembersOfB0AtInstanceSide = privateMembersOfBaseClassB0.concat(validStaticMembersOfBaseClassB0); +const invalidMembersOfB0AtStaticSide = privateMembersOfBaseClassB0.concat(validInstanceMembersOfBaseClassB0); +// members of B0 and members of I4 +verifyClassElementLocations({ + validMembers: validInstanceMembersOfBaseClassB0.concat(membersOfI4), + invalidMembers: invalidMembersOfB0AtInstanceSide +}, [ + "extendsB0ThatExtendsAndImplementsI4WithStaticMethod", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethod", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStatic" + ]); + +// members of B0 and members of I4 that are not staticMethod +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ validInstanceMembersOfBaseClassB0, + /*invalidMembers*/ invalidMembersOfB0AtInstanceSide, + /*arrayToDistribute*/ membersOfI4, + value => value[0] !== "staticMethod" + ), [ + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethod", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBoth" + ]); + +// static members of B0 +verifyClassElementLocations({ + validMembers: validStaticMembersOfBaseClassB0, + invalidMembers: invalidMembersOfB0AtStaticSide.concat(membersOfI4) +}, [ + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodWritingStatic", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethodWritingStatic", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodWritingStatic" + ]); + +// static members of B0 without staticMethod +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ noMembers, + /*invalidMembers*/ invalidMembersOfB0AtStaticSide.concat(membersOfI4), + /*arrayToDistribute*/ validStaticMembersOfBaseClassB0, + value => value[0] !== "staticMethod" + ), [ + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStaticWritingStatic", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBothWritingStatic" + ]); + +// members of I7 extends I +verifyClassElementLocations({ validMembers: membersOfI7, invalidMembers: noMembers }, [ + "implementsI7whichExtendsI", + "implementsI7whichExtendsIAndAlsoImplementsI", + "implementsIAndAlsoImplementsI7whichExtendsI" +]); + +const invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 = invalidMembersOfB0AtInstanceSide + .concat(protectedPropertiesOfBaseClassB0); +// members of I5 extends B0 +verifyClassElementLocations({ + validMembers: membersOfI5, + invalidMembers: invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 +}, [ + "implementsI5ThatExtendsB0", + ]); + +// members of I6 extends B0 +verifyClassElementLocations({ + validMembers: membersOfI6, + invalidMembers: invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 +}, [ + "implementsI6ThatExtendsB0AndHasStaticMethodOfB0", + ]); + +// members of B0 and I5 that extends B0 +verifyClassElementLocations({ + validMembers: membersOfI5.concat(protectedPropertiesOfBaseClassB0), + invalidMembers: invalidMembersOfB0AtInstanceSide +}, [ + "extendsB0AndImplementsI5ThatExtendsB0" + ]); + +// members of B0 and I6 that extends B0 +verifyClassElementLocations({ + validMembers: membersOfI6.concat(protectedPropertiesOfBaseClassB0), + invalidMembers: invalidMembersOfB0AtInstanceSide +}, [ + "extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0" + ]); + +// nothing on static side as these do not extend any other class +verifyClassElementLocations({ + validMembers: [], + invalidMembers: membersOfI5.concat(membersOfI6, invalidMembersOfB0AtStaticSide) +}, [ + "implementsI5ThatExtendsB0TypesStatic", + "implementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic" + ]); + +// statics of base B but nothing from instance side +verifyClassElementLocations({ + validMembers: validStaticMembersOfBaseClassB0, + invalidMembers: membersOfI5.concat(membersOfI6, invalidMembersOfB0AtStaticSide) +}, [ + "extendsB0AndImplementsI5ThatExtendsB0TypesStatic", + "extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic" + ]); \ No newline at end of file diff --git a/tests/cases/fourslash/completionForStringLiteral12.ts b/tests/cases/fourslash/completionForStringLiteral12.ts new file mode 100644 index 00000000000..22bb2f00a43 --- /dev/null +++ b/tests/cases/fourslash/completionForStringLiteral12.ts @@ -0,0 +1,10 @@ +/// + +////function foo(x: "bla"): void; +////function foo(x: "bla"): void; +////function foo(x: string) {} +////foo("/**/") + +goTo.marker(); +verify.completionListContains("bla"); +verify.completionListCount(1); diff --git a/tests/cases/fourslash/completionInJsDoc.ts b/tests/cases/fourslash/completionInJsDoc.ts index 60707905956..4c1bb004671 100644 --- a/tests/cases/fourslash/completionInJsDoc.ts +++ b/tests/cases/fourslash/completionInJsDoc.ts @@ -84,23 +84,18 @@ goTo.marker('8'); verify.completionListContains('number'); goTo.marker('9'); -verify.completionListCount(40); verify.completionListContains("@argument"); goTo.marker('10'); -verify.completionListCount(40); verify.completionListContains("@returns"); goTo.marker('11'); -verify.completionListCount(40); verify.completionListContains("@argument"); goTo.marker('12'); -verify.completionListCount(40); verify.completionListContains("@constructor"); goTo.marker('13'); -verify.completionListCount(40); verify.completionListContains("@param"); goTo.marker('14'); diff --git a/tests/cases/fourslash/completionListBuilderLocations_properties.ts b/tests/cases/fourslash/completionListBuilderLocations_properties.ts index 806d8c1de4f..2cdc3b7e7ba 100644 --- a/tests/cases/fourslash/completionListBuilderLocations_properties.ts +++ b/tests/cases/fourslash/completionListBuilderLocations_properties.ts @@ -10,4 +10,4 @@ //// public static a/*property2*/ ////} -goTo.eachMarker(() => verify.completionListIsEmpty()); +goTo.eachMarker(() => verify.completionListContainsClassElementKeywords()); diff --git a/tests/cases/fourslash/completionListInNamedClassExpression.ts b/tests/cases/fourslash/completionListInNamedClassExpression.ts index cf0d170f6a5..8ca6806ce7f 100644 --- a/tests/cases/fourslash/completionListInNamedClassExpression.ts +++ b/tests/cases/fourslash/completionListInNamedClassExpression.ts @@ -1,4 +1,4 @@ -/// +/// //// var x = class myClass { //// getClassName (){ @@ -11,4 +11,4 @@ goTo.marker("0"); verify.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); goTo.marker("1"); -verify.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); \ No newline at end of file +verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInNamedClassExpressionWithShadowing.ts b/tests/cases/fourslash/completionListInNamedClassExpressionWithShadowing.ts index e1274e6f592..fd347d58037 100644 --- a/tests/cases/fourslash/completionListInNamedClassExpressionWithShadowing.ts +++ b/tests/cases/fourslash/completionListInNamedClassExpressionWithShadowing.ts @@ -1,4 +1,4 @@ -/// +/// //// class myClass { /*0*/ } //// /*1*/ @@ -16,7 +16,7 @@ //// } goTo.marker("0"); -verify.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); +verify.not.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); goTo.marker("1"); @@ -28,7 +28,7 @@ verify.completionListContains("myClass", "(local class) myClass", /*documentatio verify.not.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); goTo.marker("3"); -verify.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); +verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); verify.not.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); goTo.marker("4"); @@ -36,5 +36,5 @@ verify.completionListContains("myClass", "class myClass", /*documentation*/ unde verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); goTo.marker("5"); -verify.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); +verify.not.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); diff --git a/tests/cases/fourslash/completionListIsGlobalCompletion.ts b/tests/cases/fourslash/completionListIsGlobalCompletion.ts index a1fadc6bb12..121ab940d65 100644 --- a/tests/cases/fourslash/completionListIsGlobalCompletion.ts +++ b/tests/cases/fourslash/completionListIsGlobalCompletion.ts @@ -53,7 +53,7 @@ verify.completionListIsGlobal(false); goTo.marker("9"); verify.completionListIsGlobal(false); goTo.marker("10"); -verify.completionListIsGlobal(true); +verify.completionListIsGlobal(false); goTo.marker("11"); verify.completionListIsGlobal(true); goTo.marker("12"); diff --git a/tests/cases/fourslash/completionListOfUnion.ts b/tests/cases/fourslash/completionListOfUnion.ts new file mode 100644 index 00000000000..5ffaf89e5b3 --- /dev/null +++ b/tests/cases/fourslash/completionListOfUnion.ts @@ -0,0 +1,20 @@ +/// + +// @strictNullChecks: true + +// Primitives should be skipped, so `| number | null | undefined` should have no effect on completions. +////const x: { a: number, b: number } | { a: string, c: string } | { b: boolean } | number | null | undefined = { /*x*/ }; + +////interface I { a: number; } +////function f(...args: Array) {} +////f({ /*f*/ }); + +goTo.marker("x"); +verify.completionListCount(3); +verify.completionListContains("a", "(property) a: string | number"); +verify.completionListContains("b", "(property) b: number | boolean"); +verify.completionListContains("c", "(property) c: string"); + +goTo.marker("f"); +verify.completionListContains("a", "(property) a: number"); +// Also contains array members diff --git a/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts b/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts index 51e4013e53a..916ad10fe9c 100644 --- a/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts +++ b/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts @@ -225,27 +225,28 @@ //// ////var shwvar = 1; -function goToMarkAndGeneralVerify(marker: string) +function goToMarkAndGeneralVerify(marker: string, isClassScope?: boolean) { goTo.marker(marker); - verify.completionListContains('mod1var', 'var mod1var: number'); - verify.completionListContains('mod1fn', 'function mod1fn(): void'); - verify.completionListContains('mod1cls', 'class mod1cls'); - verify.completionListContains('mod1int', 'interface mod1int'); - verify.completionListContains('mod1mod', 'namespace mod1mod'); - verify.completionListContains('mod1evar', 'var mod1.mod1evar: number'); - verify.completionListContains('mod1efn', 'function mod1.mod1efn(): void'); - verify.completionListContains('mod1ecls', 'class mod1.mod1ecls'); - verify.completionListContains('mod1eint', 'interface mod1.mod1eint'); - verify.completionListContains('mod1emod', 'namespace mod1.mod1emod'); - verify.completionListContains('mod1eexvar', 'var mod1.mod1eexvar: number'); - verify.completionListContains('mod2', 'namespace mod2'); - verify.completionListContains('mod3', 'namespace mod3'); - verify.completionListContains('shwvar', 'var shwvar: number'); - verify.completionListContains('shwfn', 'function shwfn(): void'); - verify.completionListContains('shwcls', 'class shwcls'); - verify.completionListContains('shwint', 'interface shwint'); + const verifyModule = isClassScope ? verify.not : verify; + verifyModule.completionListContains('mod1var', 'var mod1var: number'); + verifyModule.completionListContains('mod1fn', 'function mod1fn(): void'); + verifyModule.completionListContains('mod1cls', 'class mod1cls'); + verifyModule.completionListContains('mod1int', 'interface mod1int'); + verifyModule.completionListContains('mod1mod', 'namespace mod1mod'); + verifyModule.completionListContains('mod1evar', 'var mod1.mod1evar: number'); + verifyModule.completionListContains('mod1efn', 'function mod1.mod1efn(): void'); + verifyModule.completionListContains('mod1ecls', 'class mod1.mod1ecls'); + verifyModule.completionListContains('mod1eint', 'interface mod1.mod1eint'); + verifyModule.completionListContains('mod1emod', 'namespace mod1.mod1emod'); + verifyModule.completionListContains('mod1eexvar', 'var mod1.mod1eexvar: number'); + verifyModule.completionListContains('mod2', 'namespace mod2'); + verifyModule.completionListContains('mod3', 'namespace mod3'); + verifyModule.completionListContains('shwvar', 'var shwvar: number'); + verifyModule.completionListContains('shwfn', 'function shwfn(): void'); + verifyModule.completionListContains('shwcls', 'class shwcls'); + verifyModule.completionListContains('shwint', 'interface shwint'); verify.not.completionListContains('mod2var'); verify.not.completionListContains('mod2fn'); @@ -280,7 +281,7 @@ verify.completionListContains('bar', '(local var) bar: number'); verify.completionListContains('foob', '(local function) foob(): void'); // from class in mod1 -goToMarkAndGeneralVerify('class'); +goToMarkAndGeneralVerify('class', /*isClassScope*/ true); //verify.not.completionListContains('ceFunc'); //verify.not.completionListContains('ceVar'); @@ -306,7 +307,7 @@ verify.completionListContains('bar', '(local var) bar: number'); verify.completionListContains('foob', '(local function) foob(): void'); // from exported class in mod1 -goToMarkAndGeneralVerify('exportedClass'); +goToMarkAndGeneralVerify('exportedClass', /*isClassScope*/ true); //verify.not.completionListContains('ceFunc'); //verify.not.completionListContains('ceVar'); diff --git a/tests/cases/fourslash/completionListWithModulesOutsideModuleScope2.ts b/tests/cases/fourslash/completionListWithModulesOutsideModuleScope2.ts index 865887661e9..340d0bd3191 100644 --- a/tests/cases/fourslash/completionListWithModulesOutsideModuleScope2.ts +++ b/tests/cases/fourslash/completionListWithModulesOutsideModuleScope2.ts @@ -231,6 +231,39 @@ //// x: /*objectLiteral*/ ////} +goTo.marker('extendedClass'); + +verify.not.completionListContains('mod1'); +verify.not.completionListContains('mod2'); +verify.not.completionListContains('mod3'); +verify.not.completionListContains('shwvar', 'var shwvar: number'); +verify.not.completionListContains('shwfn', 'function shwfn(): void'); +verify.not.completionListContains('shwcls', 'class shwcls'); +verify.not.completionListContains('shwint', 'interface shwint'); + +verify.not.completionListContains('mod2var'); +verify.not.completionListContains('mod2fn'); +verify.not.completionListContains('mod2cls'); +verify.not.completionListContains('mod2int'); +verify.not.completionListContains('mod2mod'); +verify.not.completionListContains('mod2evar'); +verify.not.completionListContains('mod2efn'); +verify.not.completionListContains('mod2ecls'); +verify.not.completionListContains('mod2eint'); +verify.not.completionListContains('mod2emod'); +verify.not.completionListContains('sfvar'); +verify.not.completionListContains('sffn'); +verify.not.completionListContains('scvar'); +verify.not.completionListContains('scfn'); +verify.completionListContains('scpfn'); +verify.completionListContains('scpvar'); +verify.not.completionListContains('scsvar'); +verify.not.completionListContains('scsfn'); +verify.not.completionListContains('sivar'); +verify.not.completionListContains('sifn'); +verify.not.completionListContains('mod1exvar'); +verify.not.completionListContains('mod2eexvar'); + function goToMarkerAndVerify(marker: string) { goTo.marker(marker); @@ -267,8 +300,6 @@ function goToMarkerAndVerify(marker: string) verify.not.completionListContains('mod2eexvar'); } -goToMarkerAndVerify('extendedClass'); - goToMarkerAndVerify('objectLiteral'); goTo.marker('localVar'); diff --git a/tests/cases/fourslash/completionsKeyof.ts b/tests/cases/fourslash/completionsKeyof.ts new file mode 100644 index 00000000000..e3beae556c5 --- /dev/null +++ b/tests/cases/fourslash/completionsKeyof.ts @@ -0,0 +1,17 @@ +/// + +////interface A { a: number; }; +////interface B { a: number; b: number; }; +////function f(key: T) {} +////f("/*f*/"); +////function g(key: T) {} +////g("/*g*/"); + +goTo.marker("f"); +verify.completionListCount(1); +verify.completionListContains("a"); + +goTo.marker("g"); +verify.completionListCount(2); +verify.completionListContains("a"); +verify.completionListContains("b"); diff --git a/tests/cases/fourslash/convertFunctionToEs6Class1.ts b/tests/cases/fourslash/convertFunctionToEs6Class1.ts new file mode 100644 index 00000000000..6275e48e627 --- /dev/null +++ b/tests/cases/fourslash/convertFunctionToEs6Class1.ts @@ -0,0 +1,26 @@ +/// + +// @allowNonTsExtensions: true +// @Filename: test123.js +//// [|function /*1*/foo() { } +//// /*2*/foo.prototype.instanceMethod1 = function() { return "this is name"; }; +//// /*3*/foo.prototype.instanceMethod2 = () => { return "this is name"; }; +//// /*4*/foo.prototype.instanceProp1 = "hello"; +//// /*5*/foo.prototype.instanceProp2 = undefined; +//// /*6*/foo.staticProp = "world"; +//// /*7*/foo.staticMethod1 = function() { return "this is static name"; }; +//// /*8*/foo.staticMethod2 = () => "this is static name";|] + +['1', '2', '3', '4', '5', '6', '7', '8'].forEach(m => verify.applicableRefactorAvailableAtMarker(m)); +verify.fileAfterApplyingRefactorAtMarker('1', +`class foo { + constructor() { } + instanceMethod1() { return "this is name"; } + instanceMethod2() { return "this is name"; } + static staticMethod1() { return "this is static name"; } + static staticMethod2() { return "this is static name"; } +} +foo.prototype.instanceProp1 = "hello"; +foo.prototype.instanceProp2 = undefined; +foo.staticProp = "world"; +`, 'Convert to ES2015 class'); \ No newline at end of file diff --git a/tests/cases/fourslash/convertFunctionToEs6Class2.ts b/tests/cases/fourslash/convertFunctionToEs6Class2.ts new file mode 100644 index 00000000000..5d9a9f32585 --- /dev/null +++ b/tests/cases/fourslash/convertFunctionToEs6Class2.ts @@ -0,0 +1,27 @@ +/// + +// @allowNonTsExtensions: true +// @Filename: test123.js +//// [|var /*1*/foo = function() { }; +//// /*2*/foo.prototype.instanceMethod1 = function() { return "this is name"; }; +//// /*3*/foo.prototype.instanceMethod2 = () => { return "this is name"; }; +//// /*4*/foo.instanceProp1 = "hello"; +//// /*5*/foo.instanceProp2 = undefined; +//// /*6*/foo.staticProp = "world"; +//// /*7*/foo.staticMethod1 = function() { return "this is static name"; }; +//// /*8*/foo.staticMethod2 = () => "this is static name";|] + + +['1', '2', '3', '4', '5', '6', '7', '8'].forEach(m => verify.applicableRefactorAvailableAtMarker(m)); +verify.fileAfterApplyingRefactorAtMarker('4', +`class foo { + constructor() { } + instanceMethod1() { return "this is name"; } + instanceMethod2() { return "this is name"; } + static staticMethod1() { return "this is static name"; } + static staticMethod2() { return "this is static name"; } +} +foo.instanceProp1 = "hello"; +foo.instanceProp2 = undefined; +foo.staticProp = "world"; +`, 'Convert to ES2015 class'); diff --git a/tests/cases/fourslash/convertFunctionToEs6Class3.ts b/tests/cases/fourslash/convertFunctionToEs6Class3.ts new file mode 100644 index 00000000000..af8955dcb71 --- /dev/null +++ b/tests/cases/fourslash/convertFunctionToEs6Class3.ts @@ -0,0 +1,28 @@ +/// + +// @allowNonTsExtensions: true +// @Filename: test123.js +//// [|var bar = 10, /*1*/foo = function() { }; +//// /*2*/foo.prototype.instanceMethod1 = function() { return "this is name"; }; +//// /*3*/foo.prototype.instanceMethod2 = () => { return "this is name"; }; +//// /*4*/foo.prototype.instanceProp1 = "hello"; +//// /*5*/foo.prototype.instanceProp2 = undefined; +//// /*6*/foo.staticProp = "world"; +//// /*7*/foo.staticMethod1 = function() { return "this is static name"; }; +//// /*8*/foo.staticMethod2 = () => "this is static name";|] + + +['1', '2', '3', '4', '5', '6', '7', '8'].forEach(m => verify.applicableRefactorAvailableAtMarker(m)); +verify.fileAfterApplyingRefactorAtMarker('7', +`var bar = 10; +class foo { + constructor() { } + instanceMethod1() { return "this is name"; } + instanceMethod2() { return "this is name"; } + static staticMethod1() { return "this is static name"; } + static staticMethod2() { return "this is static name"; } +} +foo.prototype.instanceProp1 = "hello"; +foo.prototype.instanceProp2 = undefined; +foo.staticProp = "world"; +`, 'Convert to ES2015 class'); \ No newline at end of file diff --git a/tests/cases/fourslash/findAllRefsEnumAsNamespace.ts b/tests/cases/fourslash/findAllRefsEnumAsNamespace.ts new file mode 100644 index 00000000000..a065f355d10 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsEnumAsNamespace.ts @@ -0,0 +1,6 @@ +/// + +////enum [|{| "isWriteAccess": true, "isDefinition": true |}E|] { A } +////let e: [|E|].A; + +verify.singleReferenceGroup("enum E"); diff --git a/tests/cases/fourslash/findAllRefsEnumMember.ts b/tests/cases/fourslash/findAllRefsEnumMember.ts new file mode 100644 index 00000000000..584b8befd29 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsEnumMember.ts @@ -0,0 +1,6 @@ +/// + +////enum E { [|{| "isWriteAccess": true, "isDefinition": true |}A|], B } +////const e: E.[|A|] = E.[|A|]; + +verify.singleReferenceGroup("(enum member) E.A = 0"); diff --git a/tests/cases/fourslash/findAllRefsForDefaultExport04.ts b/tests/cases/fourslash/findAllRefsForDefaultExport04.ts new file mode 100644 index 00000000000..c8fdb0a6149 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsForDefaultExport04.ts @@ -0,0 +1,16 @@ +/// + +// @Filename: /a.ts +////const [|{| "isWriteAccess": true, "isDefinition": true |}a|] = 0; +////export default [|a|]; + +// @Filename: /b.ts +////import [|{| "isWriteAccess": true, "isDefinition": true |}a|] from "./a"; +////[|a|]; + +const [r0, r1, r2, r3] = test.ranges(); +verify.referenceGroups([r0, r1], [ + { definition: "const a: 0", ranges: [r0, r1] }, + { definition: "import a", ranges: [r2, r3] } +]); +verify.singleReferenceGroup("import a", [r2, r3]); diff --git a/tests/cases/fourslash/findAllRefsForModule.ts b/tests/cases/fourslash/findAllRefsForModule.ts new file mode 100644 index 00000000000..ae6b216463f --- /dev/null +++ b/tests/cases/fourslash/findAllRefsForModule.ts @@ -0,0 +1,23 @@ +/// + +// @allowJs: true + +// @Filename: /a.ts +////export const x = 0; + +// @Filename: /b.ts +////import { x } from "[|./a|]"; + +// @Filename: /c/sub.js +////const a = require("[|../a|]"); + +// @Filename: /d.ts +//// /// + +verify.noErrors(); + +const ranges = test.ranges(); +const [r0, r1, r2] = ranges; +verify.referenceGroups([r0, r1], [{ definition: 'module "/a"', ranges: [r0, r2, r1] }]); +// TODO:GH#15736 +verify.referenceGroups(r2, undefined); diff --git a/tests/cases/fourslash/findAllRefsForModuleGlobal.ts b/tests/cases/fourslash/findAllRefsForModuleGlobal.ts new file mode 100644 index 00000000000..4c1b39cdb0f --- /dev/null +++ b/tests/cases/fourslash/findAllRefsForModuleGlobal.ts @@ -0,0 +1,17 @@ +/// + +// @Filename: /node_modules/foo/index.d.ts +////export const x = 0; + +// @Filename: /b.ts +/////// +////import { x } from "[|foo|]"; +////declare module "[|{| "isWriteAccess": true, "isDefinition": true |}foo|]" {} + +verify.noErrors(); + +const ranges = test.ranges(); +const [r0, r1, r2] = ranges; +verify.referenceGroups([r1, r2], [{ definition: 'module "/node_modules/foo/index"', ranges: [r0, r1, r2] }]); +// TODO:GH#15736 +verify.referenceGroups(r0, undefined); diff --git a/tests/cases/fourslash/findAllRefsJsDocTypeDef.ts b/tests/cases/fourslash/findAllRefsJsDocTypeDef.ts new file mode 100644 index 00000000000..204a4748686 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsJsDocTypeDef.ts @@ -0,0 +1,9 @@ +/// + +// Just testing that this doesn't cause an exception due to the @typedef contents not having '.parent' set. +// But it isn't bound to a Symbol so find-all-refs will return nothing. + +/////** @typedef {Object} [|T|] */ +////function foo() {} + +verify.referenceGroups(test.ranges()[0], undefined); diff --git a/tests/cases/fourslash/findAllRefsMappedType.ts b/tests/cases/fourslash/findAllRefsMappedType.ts new file mode 100644 index 00000000000..7daf0296d94 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsMappedType.ts @@ -0,0 +1,15 @@ +/// + +////interface T { [|{| "isWriteAccess": true, "isDefinition": true |}a|]: number; } +////type U = { readonly [K in keyof T]?: string }; +////declare const t: T; +////t.[|a|]; +////declare const u: U; +////u.[|a|]; + +const ranges = test.ranges(); +const [r0, r1, r2] = ranges; +verify.referenceGroups([r0, r1], [{ definition: "(property) T.a: number", ranges }]); +verify.referenceGroups(r2, [ + { definition: "(property) T.a: number", ranges: [r0, r1] }, + { definition: "(property) a: string", ranges: [r2] }]); diff --git a/tests/cases/fourslash/findAllRefsOnImportAliases2.ts b/tests/cases/fourslash/findAllRefsOnImportAliases2.ts index 63fb12f5270..64f44018d07 100644 --- a/tests/cases/fourslash/findAllRefsOnImportAliases2.ts +++ b/tests/cases/fourslash/findAllRefsOnImportAliases2.ts @@ -1,16 +1,14 @@ /// //@Filename: a.ts -////export class [|{| "isWriteAccess": true, "isDefinition": true |}Class|] { -////} +////export class [|{| "isWriteAccess": true, "isDefinition": true |}Class|] {} //@Filename: b.ts -////import { [|{| "isWriteAccess": true, "isDefinition": true |}Class|] as [|{| "isWriteAccess": true, "isDefinition": true |}C2|] } from "./a"; -//// +////import { [|Class|] as [|{| "isWriteAccess": true, "isDefinition": true |}C2|] } from "./a"; ////var c = new [|C2|](); //@Filename: c.ts -////export { [|{| "isWriteAccess": true, "isDefinition": true |}Class|] as [|{| "isWriteAccess": true, "isDefinition": true |}C3|] } from "./a"; +////export { [|Class|] as [|{| "isWriteAccess": true, "isDefinition": true |}C3|] } from "./a"; const ranges = test.rangesByText(); const classRanges = ranges.get("Class"); diff --git a/tests/cases/fourslash/findAllRefsPrimitiveJsDoc.ts b/tests/cases/fourslash/findAllRefsPrimitiveJsDoc.ts new file mode 100644 index 00000000000..82daf720d19 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsPrimitiveJsDoc.ts @@ -0,0 +1,11 @@ +// @noLib: true + +/// + +/////** +//// * @param {[|number|]} n +//// * @returns {[|number|]} +//// */ +////function f(n: [|number|]): [|number|] {} + +verify.singleReferenceGroup("number"); diff --git a/tests/cases/fourslash/findAllRefsReExportLocal.ts b/tests/cases/fourslash/findAllRefsReExportLocal.ts index 25e8accbbc0..3e5890e6317 100644 --- a/tests/cases/fourslash/findAllRefsReExportLocal.ts +++ b/tests/cases/fourslash/findAllRefsReExportLocal.ts @@ -5,7 +5,7 @@ // @Filename: /a.ts ////var [|{| "isWriteAccess": true, "isDefinition": true |}x|]; ////export { [|{| "isWriteAccess": true, "isDefinition": true |}x|] }; -////export { [|{| "isWriteAccess": true, "isDefinition": true |}x|] as [|{| "isWriteAccess": true, "isDefinition": true |}y|] }; +////export { [|x|] as [|{| "isWriteAccess": true, "isDefinition": true |}y|] }; // @Filename: /b.ts ////import { [|{| "isWriteAccess": true, "isDefinition": true |}x|], [|{| "isWriteAccess": true, "isDefinition": true |}y|] } from "./a"; diff --git a/tests/cases/fourslash/findAllRefsReExports.ts b/tests/cases/fourslash/findAllRefsReExports.ts index 593db568c8a..a4cced049b9 100644 --- a/tests/cases/fourslash/findAllRefsReExports.ts +++ b/tests/cases/fourslash/findAllRefsReExports.ts @@ -4,10 +4,10 @@ ////export function [|{| "isWriteAccess": true, "isDefinition": true |}foo|](): void {} // @Filename: /b.ts -////export { [|{| "isWriteAccess": true, "isDefinition": true |}foo|] as [|{| "isWriteAccess": true, "isDefinition": true |}bar|] } from "./a"; +////export { [|foo|] as [|{| "isWriteAccess": true, "isDefinition": true |}bar|] } from "./a"; // @Filename: /c.ts -////export { [|{| "isWriteAccess": true, "isDefinition": true |}foo|] as [|{| "isWriteAccess": true, "isDefinition": true |}default|] } from "./a"; +////export { [|foo|] as [|{| "isWriteAccess": true, "isDefinition": true |}default|] } from "./a"; // @Filename: /d.ts ////export { [|{| "isWriteAccess": true, "isDefinition": true |}default|] } from "./c"; @@ -15,7 +15,7 @@ // @Filename: /e.ts ////import { [|{| "isWriteAccess": true, "isDefinition": true |}bar|] } from "./b"; ////import [|{| "isWriteAccess": true, "isDefinition": true |}baz|] from "./c"; -////import { [|{| "isWriteAccess": true, "isDefinition": true |}default|] as [|{| "isWriteAccess": true, "isDefinition": true |}bang|] } from "./c"; +////import { [|default|] as [|{| "isWriteAccess": true, "isDefinition": true |}bang|] } from "./c"; ////import [|{| "isWriteAccess": true, "isDefinition": true |}boom|] from "./d"; ////[|bar|](); [|baz|](); [|bang|](); [|boom|](); diff --git a/tests/cases/fourslash/findAllRefsReExports2.ts b/tests/cases/fourslash/findAllRefsReExports2.ts new file mode 100644 index 00000000000..5dfdc8aebbf --- /dev/null +++ b/tests/cases/fourslash/findAllRefsReExports2.ts @@ -0,0 +1,14 @@ +/// + +// @Filename: /a.ts +////export function [|{| "isWriteAccess": true, "isDefinition": true |}foo|](): void {} + +// @Filename: /b.ts +////import { [|foo|] as [|{| "isWriteAccess": true, "isDefinition": true |}oof|] } from "./a"; + +verify.noErrors(); +const [r0, r1, r2] = test.ranges(); +verify.referenceGroups(r0, [ + { definition: "function foo(): void", ranges: [r0, r1] }, + { definition: "import oof", ranges: [r2] } +]); diff --git a/tests/cases/fourslash/findAllRefsRenameImportWithSameName.ts b/tests/cases/fourslash/findAllRefsRenameImportWithSameName.ts index c1a49b3b5b0..5a5db1496a7 100644 --- a/tests/cases/fourslash/findAllRefsRenameImportWithSameName.ts +++ b/tests/cases/fourslash/findAllRefsRenameImportWithSameName.ts @@ -4,7 +4,7 @@ ////export const [|{| "isWriteAccess": true, "isDefinition": true |}x|] = 0; //@Filename: /b.ts -////import { [|{| "isWriteAccess": true, "isDefinition": true |}x|] as [|{| "isWriteAccess": true, "isDefinition": true |}x|] } from "./a"; +////import { [|x|] as [|{| "isWriteAccess": true, "isDefinition": true |}x|] } from "./a"; ////[|x|]; verify.noErrors(); diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 374dfd33c7d..3fada673f35 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -133,11 +133,13 @@ declare namespace FourSlashInterface { class verifyNegatable { private negative; not: verifyNegatable; + allowedClassElementKeywords: string[]; constructor(negative?: boolean); completionListCount(expectedCount: number): void; completionListContains(symbol: string, text?: string, documentation?: string, kind?: string, spanIndex?: number): void; completionListItemsCountIsGreaterThan(count: number): void; completionListIsEmpty(): void; + completionListContainsClassElementKeywords(): void; completionListAllowsNewIdentifier(): void; signatureHelpPresent(): void; errorExistsBetweenMarkers(startMarker: string, endMarker: string): void; @@ -148,6 +150,9 @@ declare namespace FourSlashInterface { implementationListIsEmpty(): void; isValidBraceCompletionAtPosition(openingBrace?: string): void; codeFixAvailable(): void; + applicableRefactorAvailableAtMarker(markerName: string): void; + codeFixDiagnosticsAvailableAtMarkers(markerNames: string[], diagnosticCode?: number): void; + applicableRefactorAvailableForRange(): void; } class verify extends verifyNegatable { assertHasRanges(ranges: Range[]): void; @@ -232,6 +237,7 @@ declare namespace FourSlashInterface { DocCommentTemplate(expectedText: string, expectedOffset: number, empty?: boolean): void; noDocCommentTemplate(): void; rangeAfterCodeFix(expectedText: string, includeWhiteSpace?: boolean, errorCode?: number, index?: number): void; + fileAfterApplyingRefactorAtMarker(markerName: string, expectedContent: string, refactorNameToApply: string, formattingOptions?: FormatCodeOptions): void; importFixAtPosition(expectedTextArray: string[], errorCode?: number): void; navigationBar(json: any): void; diff --git a/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts b/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts index 27c34e56600..7d6cb0a48af 100644 --- a/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts +++ b/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts @@ -6,4 +6,4 @@ const ranges = test.ranges(); const [r0, r1, r2] = ranges; verify.referenceGroups(r0, [{ definition: '(property) ["foo"]: number', ranges }]); -verify.referenceGroups([r1, r2], []); // TODO: fix +verify.referenceGroups([r1, r2], undefined); // TODO: fix diff --git a/tests/cases/fourslash/getOccurrencesIsDefinitionOfNumberNamedProperty.ts b/tests/cases/fourslash/getOccurrencesIsDefinitionOfNumberNamedProperty.ts index c603f398e5e..b391deec9cc 100644 --- a/tests/cases/fourslash/getOccurrencesIsDefinitionOfNumberNamedProperty.ts +++ b/tests/cases/fourslash/getOccurrencesIsDefinitionOfNumberNamedProperty.ts @@ -1,5 +1,5 @@ /// -////let o = { [|{| "isDefinition": true |}1|]: 12 }; +////let o = { [|{| "isWriteAccess": true, "isDefinition": true |}1|]: 12 }; ////let y = o[[|1|]]; const ranges = test.ranges(); diff --git a/tests/cases/fourslash/getOccurrencesIsDefinitionOfStringNamedProperty.ts b/tests/cases/fourslash/getOccurrencesIsDefinitionOfStringNamedProperty.ts index 43fe0c571fc..4b842da6f59 100644 --- a/tests/cases/fourslash/getOccurrencesIsDefinitionOfStringNamedProperty.ts +++ b/tests/cases/fourslash/getOccurrencesIsDefinitionOfStringNamedProperty.ts @@ -1,5 +1,5 @@ /// -////let o = { "[|{| "isDefinition": true |}x|]": 12 }; +////let o = { "[|{| "isWriteAccess": true, "isDefinition": true |}x|]": 12 }; ////let y = o.[|x|]; const ranges = test.ranges(); diff --git a/tests/cases/fourslash/getPreProcessedFile.ts b/tests/cases/fourslash/getPreProcessedFile.ts index 03ce481c8ba..a33a6c9a470 100644 --- a/tests/cases/fourslash/getPreProcessedFile.ts +++ b/tests/cases/fourslash/getPreProcessedFile.ts @@ -5,12 +5,12 @@ //// class D { } // @Filename: refFile2.ts -//// export class E {} +//// export class E {} // @Filename: main.ts // @ResolveReference: true //// /// -//// /*1*/////*2*/ +//// /// //// /*3*/////*4*/ //// import ref2 = require("refFile2"); //// import noExistref2 = require(/*5*/"NotExistRefFile2"/*6*/); diff --git a/tests/cases/fourslash/goToDefinitionImports.ts b/tests/cases/fourslash/goToDefinitionImports.ts new file mode 100644 index 00000000000..4fdaedb5c3d --- /dev/null +++ b/tests/cases/fourslash/goToDefinitionImports.ts @@ -0,0 +1,26 @@ +/// + +// @Filename: /a.ts +////export default function /*fDef*/f() {} +////export const /*xDef*/x = 0; + +// @Filename: /b.ts +/////*bDef*/declare const b: number; +////export = b; + +// @Filename: /b.ts +////import f, { x } from "./a"; +////import * as /*aDef*/a from "./a"; +////import b = require("./b"); +/////*fUse*/f; +/////*xUse*/x; +/////*aUse*/a; +/////*bUse*/b; + +verify.goToDefinition({ + aUse: "aDef", // Namespace import isn't "skipped" + fUse: "fDef", + xUse: "xDef", + bUse: "bDef", +}); + diff --git a/tests/cases/fourslash/goToDefinition_untypedModule.ts b/tests/cases/fourslash/goToDefinition_untypedModule.ts index b4571438434..fe29f7104cf 100644 --- a/tests/cases/fourslash/goToDefinition_untypedModule.ts +++ b/tests/cases/fourslash/goToDefinition_untypedModule.ts @@ -4,7 +4,7 @@ ////not read // @Filename: /a.ts -////import { f } from "foo"; -/////**/f(); +////import { /*def*/f } from "foo"; +/////*use*/f(); -verify.goToDefinition("", []); +verify.goToDefinition("use", "def"); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport0.ts b/tests/cases/fourslash/importNameCodeFixExistingImport0.ts index 5e5be220688..e5b63499878 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport0.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport0.ts @@ -7,4 +7,4 @@ //// export function f1() {} //// export var v1 = 5; -verify.importFixAtPosition([`{ v1, f1 }`]); \ No newline at end of file +verify.importFixAtPosition([`{ v1, f1 }`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport1.ts b/tests/cases/fourslash/importNameCodeFixExistingImport1.ts index 9571d0fcf57..49680692b6c 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport1.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport1.ts @@ -8,4 +8,4 @@ //// export var v1 = 5; //// export default var d1 = 6; -verify.importFixAtPosition([`{ v1, f1 }`]); \ No newline at end of file +verify.importFixAtPosition([`{ v1, f1 }`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport10.ts b/tests/cases/fourslash/importNameCodeFixExistingImport10.ts index 8a178e72730..a9525d272da 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport10.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport10.ts @@ -18,4 +18,4 @@ verify.importFixAtPosition([ v2, f1 }` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport11.ts b/tests/cases/fourslash/importNameCodeFixExistingImport11.ts index 8822356c13a..786e0e39775 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport11.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport11.ts @@ -18,4 +18,4 @@ verify.importFixAtPosition([ v3, f1 }` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport12.ts b/tests/cases/fourslash/importNameCodeFixExistingImport12.ts index e00dee504c5..87ba29ab0aa 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport12.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport12.ts @@ -9,4 +9,4 @@ //// export var v2 = 5; //// export var v3 = 5; -verify.importFixAtPosition([`{ f1 }`]); \ No newline at end of file +verify.importFixAtPosition([`{ f1 }`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport2.ts b/tests/cases/fourslash/importNameCodeFixExistingImport2.ts index 6a92976f4ef..1146f24aeae 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport2.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport2.ts @@ -12,5 +12,5 @@ verify.importFixAtPosition([ import { f1 } from "./module"; f1();`, `import * as ns from "./module"; -ns.f1();` -]); \ No newline at end of file +ns.f1();`, +]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport3.ts b/tests/cases/fourslash/importNameCodeFixExistingImport3.ts index bc00e8d420a..9fc44378713 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport3.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport3.ts @@ -14,5 +14,5 @@ verify.importFixAtPosition([ ns.f1();`, `import d, * as ns from "./module" ; import { f1 } from "./module"; -f1();`, -]); \ No newline at end of file +f1();` +]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport4.ts b/tests/cases/fourslash/importNameCodeFixExistingImport4.ts index d93cb73664e..1aaf34f598c 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport4.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport4.ts @@ -11,4 +11,4 @@ verify.importFixAtPosition([ `import d, { f1 } from "./module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport5.ts b/tests/cases/fourslash/importNameCodeFixExistingImport5.ts index ed9297124d9..bfcf888b17b 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport5.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport5.ts @@ -9,4 +9,4 @@ verify.importFixAtPosition([`import "./module"; import { f1 } from "./module"; -f1();`]); \ No newline at end of file +f1();`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport6.ts b/tests/cases/fourslash/importNameCodeFixExistingImport6.ts index 7ae157a51ce..0d3636e4439 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport6.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport6.ts @@ -10,4 +10,4 @@ //// export var v1 = 5; //// export function f1(); -verify.importFixAtPosition([`{ v1, f1 }`]); \ No newline at end of file +verify.importFixAtPosition([`{ v1, f1 }`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport7.ts b/tests/cases/fourslash/importNameCodeFixExistingImport7.ts index 249929eabc7..f0b1a77f690 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport7.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport7.ts @@ -7,4 +7,4 @@ //// export var v1 = 5; //// export function f1(); -verify.importFixAtPosition([`{ v1, f1 }`]); \ No newline at end of file +verify.importFixAtPosition([`{ v1, f1 }`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport8.ts b/tests/cases/fourslash/importNameCodeFixExistingImport8.ts index da7beaa0a47..a1b676a8b83 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport8.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport8.ts @@ -9,4 +9,4 @@ //// export var v2 = 5; //// export var v3 = 5; -verify.importFixAtPosition([`{v1, v2, v3, f1,}`]); \ No newline at end of file +verify.importFixAtPosition([`{v1, v2, v3, f1,}`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport9.ts b/tests/cases/fourslash/importNameCodeFixExistingImport9.ts index 51496abff12..67960de32d4 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport9.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport9.ts @@ -13,4 +13,4 @@ verify.importFixAtPosition([ `{ v1, f1 }` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImportEquals0.ts b/tests/cases/fourslash/importNameCodeFixExistingImportEquals0.ts index f431e6356d1..de86ed13cd5 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImportEquals0.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImportEquals0.ts @@ -15,4 +15,4 @@ var x = ns.v1 + 5;`, `import ns = require("ambient-module"); import { v1 } from "ambient-module"; var x = v1 + 5;`, -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportAmbient0.ts b/tests/cases/fourslash/importNameCodeFixNewImportAmbient0.ts index 1d7b5bc3e7f..75ef89ee4a5 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportAmbient0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportAmbient0.ts @@ -12,4 +12,4 @@ verify.importFixAtPosition([ `import { f1 } from "ambient-module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportAmbient1.ts b/tests/cases/fourslash/importNameCodeFixNewImportAmbient1.ts index 60504c89711..835850306f6 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportAmbient1.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportAmbient1.ts @@ -25,4 +25,4 @@ verify.importFixAtPosition([ `import * as ns from "yet-another-ambient-module"; import { v1 } from "ambient-module"; var x = v1 + 5;` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportAmbient2.ts b/tests/cases/fourslash/importNameCodeFixNewImportAmbient2.ts index 999da4bffbb..a23d7684d0a 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportAmbient2.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportAmbient2.ts @@ -18,4 +18,4 @@ verify.importFixAtPosition([ import { f1 } from "ambient-module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportAmbient3.ts b/tests/cases/fourslash/importNameCodeFixNewImportAmbient3.ts index 648293cce2e..dbd6c4ef26a 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportAmbient3.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportAmbient3.ts @@ -27,4 +27,4 @@ verify.importFixAtPosition([ `import * as ns from "yet-another-ambient-module" import { v1 } from "ambient-module"; var x = v1 + 5;` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts b/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts index e15c2cf4399..a48b381df68 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts @@ -16,4 +16,4 @@ verify.importFixAtPosition([ `import { f1 } from "b"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportDefault0.ts b/tests/cases/fourslash/importNameCodeFixNewImportDefault0.ts index 3efe023e922..b27cbde3283 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportDefault0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportDefault0.ts @@ -9,4 +9,4 @@ verify.importFixAtPosition([ `import f1 from "./module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts b/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts index 2372110437a..12566de406d 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts @@ -10,4 +10,4 @@ verify.importFixAtPosition([ `import { f1 } from "./module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFile1.ts b/tests/cases/fourslash/importNameCodeFixNewImportFile1.ts index 9f6cac0b7c1..b98345db9f6 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportFile1.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportFile1.ts @@ -15,4 +15,4 @@ verify.importFixAtPosition([ import { f1 } from "./Module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFile2.ts b/tests/cases/fourslash/importNameCodeFixNewImportFile2.ts index ca9330e9846..5d5c1fb61bc 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportFile2.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportFile2.ts @@ -10,4 +10,4 @@ verify.importFixAtPosition([ `import { f1 } from "../../other_dir/module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFromAtTypes.ts b/tests/cases/fourslash/importNameCodeFixNewImportFromAtTypes.ts new file mode 100644 index 00000000000..bca8f716200 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportFromAtTypes.ts @@ -0,0 +1,13 @@ +/// + +//// [|f1/*0*/();|] + +// @Filename: node_modules/@types/myLib/index.d.ts +//// export function f1() {} +//// export var v1 = 5; + +verify.importFixAtPosition([ +`import { f1 } from "myLib"; + +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFromAtTypesScopedPackage.ts b/tests/cases/fourslash/importNameCodeFixNewImportFromAtTypesScopedPackage.ts new file mode 100644 index 00000000000..3cf6cf8a32e --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportFromAtTypesScopedPackage.ts @@ -0,0 +1,13 @@ +/// + +//// [|f1/*0*/();|] + +// @Filename: node_modules/@types/myLib__scoped/index.d.ts +//// export function f1() {} +//// export var v1 = 5; + +verify.importFixAtPosition([ +`import { f1 } from "@myLib/scoped"; + +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules1.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules1.ts index 6bffe41b27a..77b1545e3c0 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules1.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules1.ts @@ -13,4 +13,4 @@ verify.importFixAtPosition([ `import { f1 } from "fake-module/nested"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules2.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules2.ts index ff48fbe182c..80cb53d7e09 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules2.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules2.ts @@ -22,4 +22,4 @@ verify.importFixAtPosition([ `import { f1 } from "fake-module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules3.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules3.ts index b1143cb4b41..f0e09885a6b 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules3.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules3.ts @@ -11,4 +11,4 @@ verify.importFixAtPosition([ `import { f1 } from "random"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportPaths0.ts b/tests/cases/fourslash/importNameCodeFixNewImportPaths0.ts index 93cd6f92ef5..bd3fd9a84b3 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportPaths0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportPaths0.ts @@ -19,4 +19,4 @@ verify.importFixAtPosition([ `import { foo } from "a"; foo();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportPaths1.ts b/tests/cases/fourslash/importNameCodeFixNewImportPaths1.ts index bb0f1e6705a..5ac195e9ab4 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportPaths1.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportPaths1.ts @@ -19,4 +19,4 @@ verify.importFixAtPosition([ `import { foo } from "b/f2"; foo();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportPaths2.ts b/tests/cases/fourslash/importNameCodeFixNewImportPaths2.ts index b455538de08..33b8d9330be 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportPaths2.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportPaths2.ts @@ -25,4 +25,4 @@ verify.importFixAtPosition([ `import { foo } from "b"; foo();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportRootDirs0.ts b/tests/cases/fourslash/importNameCodeFixNewImportRootDirs0.ts index ae8ef03ccac..8721d7e0105 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportRootDirs0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportRootDirs0.ts @@ -20,4 +20,4 @@ verify.importFixAtPosition([ `import { foo } from "./f2"; foo();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots0.ts b/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots0.ts index a6eb6a90759..cb7ef465aff 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots0.ts @@ -19,4 +19,4 @@ verify.importFixAtPosition([ `import { foo } from "random"; foo();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots1.ts b/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots1.ts index 2778f51bacf..1398a5d7866 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots1.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots1.ts @@ -20,4 +20,4 @@ verify.importFixAtPosition([ `import { foo } from "random"; foo();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts b/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts index 30b482a94d7..34cebad9415 100644 --- a/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts +++ b/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts @@ -17,4 +17,4 @@ foo();`, `import * as ns from "./foo"; ns.foo();`, -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts b/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts index 343b0692260..7a3d19e1532 100644 --- a/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts +++ b/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts @@ -17,4 +17,4 @@ foo();`, `import { foo } from "bar"; foo();`, -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/javaScriptClass3.ts b/tests/cases/fourslash/javaScriptClass3.ts index 41ce79b35eb..fd67f6f53a5 100644 --- a/tests/cases/fourslash/javaScriptClass3.ts +++ b/tests/cases/fourslash/javaScriptClass3.ts @@ -1,13 +1,13 @@ /// -// In an inferred class, we can to-to-def successfully +// In an inferred class, we can go-to-def successfully // @allowNonTsExtensions: true // @Filename: Foo.js //// class Foo { //// constructor() { -//// /*dst1*/this.alpha = 10; -//// /*dst2*/this.beta = 'gamma'; +//// this./*dst1*/alpha = 10; +//// this./*dst2*/beta = 'gamma'; //// } //// method() { return this.alpha; } //// } diff --git a/tests/cases/fourslash/jsDocServices.ts b/tests/cases/fourslash/jsDocServices.ts new file mode 100644 index 00000000000..df1e985f876 --- /dev/null +++ b/tests/cases/fourslash/jsDocServices.ts @@ -0,0 +1,24 @@ +/// + +// Note: We include the word "foo" in the documentation to test for a bug where +// the `.getChildren()` of the JSDocParameterTag included an identifier at that position with no '.text'. +////interface /*I*/I {} +//// +/////** +//// * @param /*use*/[|foo|] I pity the foo +//// */ +////function f([|/*def*/{| "isWriteAccess": true, "isDefinition": true |}foo|]: I) { +//// return [|foo|]; +////} + +const ranges = test.ranges(); +goTo.marker("use"); +verify.goToDefinitionIs("def"); +verify.goToType("use", "I"); + +goTo.marker("use"); +verify.quickInfoIs("(parameter) foo: I", "I pity the foo"); + +verify.singleReferenceGroup("(parameter) foo: I"); +verify.rangesAreDocumentHighlights(); +verify.rangesAreRenameLocations(); diff --git a/tests/cases/fourslash/jsDocTypeTagQuickInfo1.ts b/tests/cases/fourslash/jsDocTypeTagQuickInfo1.ts new file mode 100644 index 00000000000..240c00e2283 --- /dev/null +++ b/tests/cases/fourslash/jsDocTypeTagQuickInfo1.ts @@ -0,0 +1,43 @@ +/// +// @allowJs: true +// @Filename: jsDocTypeTag1.js +//// /** @type {String} */ +//// var /*1*/S; + +//// /** @type {Number} */ +//// var /*2*/N; + +//// /** @type {Boolean} */ +//// var /*3*/B; + +//// /** @type {Void} */ +//// var /*4*/V; + +//// /** @type {Undefined} */ +//// var /*5*/U; + +//// /** @type {Null} */ +//// var /*6*/Nl; + +//// /** @type {Array} */ +//// var /*7*/A; + +//// /** @type {Promise} */ +//// var /*8*/P; + +//// /** @type {Object} */ +//// var /*9*/Obj; + +//// /** @type {Function} */ +//// var /*10*/Func; + +//// /** @type {*} */ +//// var /*11*/AnyType; + +//// /** @type {?} */ +//// var /*12*/QType; + +//// /** @type {String|Number} */ +//// var /*13*/SOrN; + +verify.baselineQuickInfo(); \ No newline at end of file diff --git a/tests/cases/fourslash/jsDocTypeTagQuickInfo2.ts b/tests/cases/fourslash/jsDocTypeTagQuickInfo2.ts new file mode 100644 index 00000000000..7c79116b041 --- /dev/null +++ b/tests/cases/fourslash/jsDocTypeTagQuickInfo2.ts @@ -0,0 +1,40 @@ +/// +// @allowJs: true +// @Filename: jsDocTypeTag2.js +//// /** @type {string} */ +//// var /*1*/s; + +//// /** @type {number} */ +//// var /*2*/n; + +//// /** @type {boolean} */ +//// var /*3*/b; + +//// /** @type {void} */ +//// var /*4*/v; + +//// /** @type {undefined} */ +//// var /*5*/u; + +//// /** @type {null} */ +//// var /*6*/nl; + +//// /** @type {array} */ +//// var /*7*/a; + +//// /** @type {promise} */ +//// var /*8*/p; + +//// /** @type {?number} */ +//// var /*9*/nullable; + +//// /** @type {function} */ +//// var /*10*/func; + +//// /** @type {function (number): number} */ +//// var /*11*/func1; + +//// /** @type {string | number} */ +//// var /*12*/sOrn; + +verify.baselineQuickInfo(); \ No newline at end of file diff --git a/tests/cases/fourslash/quickInfoForRequire.ts b/tests/cases/fourslash/quickInfoForRequire.ts index e97810401f4..fe923945429 100644 --- a/tests/cases/fourslash/quickInfoForRequire.ts +++ b/tests/cases/fourslash/quickInfoForRequire.ts @@ -8,4 +8,3 @@ goTo.marker("1"); verify.quickInfoIs("module a"); -verify.noReferences(); diff --git a/tests/cases/fourslash/quickInfoMeaning.ts b/tests/cases/fourslash/quickInfoMeaning.ts index a3b9f988e1d..2c7aa5a0ccd 100644 --- a/tests/cases/fourslash/quickInfoMeaning.ts +++ b/tests/cases/fourslash/quickInfoMeaning.ts @@ -8,13 +8,13 @@ // @Filename: foo.d.ts ////declare const /*foo_value_declaration*/foo: number; ////declare module "foo_module" { -//// interface I { x: number; y: number } +//// interface /*foo_type_declaration*/I { x: number; y: number } //// export = I; ////} // @Filename: foo_user.ts /////// -////import /*foo_type_declaration*/foo = require("foo_module"); +////import foo = require("foo_module"); ////const x = foo/*foo_value*/; ////const i: foo/*foo_type*/ = { x: 1, y: 2 }; @@ -39,13 +39,13 @@ verify.goToDefinitionIs("foo_type_declaration"); // @Filename: bar.d.ts ////declare interface /*bar_type_declaration*/bar { x: number; y: number } ////declare module "bar_module" { -//// const x: number; +//// const /*bar_value_declaration*/x: number; //// export = x; ////} // @Filename: bar_user.ts /////// -////import /*bar_value_declaration*/bar = require("bar_module"); +////import bar = require("bar_module"); ////const x = bar/*bar_value*/; ////const i: bar/*bar_type*/ = { x: 1, y: 2 }; diff --git a/tests/cases/fourslash/quickInfoOnMethodOfImportEquals.ts b/tests/cases/fourslash/quickInfoOnMethodOfImportEquals.ts new file mode 100644 index 00000000000..d4078020add --- /dev/null +++ b/tests/cases/fourslash/quickInfoOnMethodOfImportEquals.ts @@ -0,0 +1,16 @@ +/// + +// Test for https://github.com/Microsoft/TypeScript/issues/15931 + +// @Filename: /a.d.ts +////declare class C { +//// m(): void; +////} +////export = C; + +// @Filename: /b.ts +////import C = require("./a"); +////declare var x: C; +////x./**/m; + +verify.quickInfoAt("", "(method) C.m(): void", undefined); diff --git a/tests/cases/fourslash/referencesBloomFilters.ts b/tests/cases/fourslash/referencesBloomFilters.ts index c9f290db0db..2745f6144ca 100644 --- a/tests/cases/fourslash/referencesBloomFilters.ts +++ b/tests/cases/fourslash/referencesBloomFilters.ts @@ -12,7 +12,7 @@ ////function blah2() { container["[|searchProp|]"] }; // @Filename: redeclaration.ts -////container = { "[|{| "isDefinition": true |}searchProp|]" : 18 }; +////container = { "[|{| "isWriteAccess": true, "isDefinition": true |}searchProp|]" : 18 }; const ranges = test.ranges(); const [r0, r1, r2, r3] = ranges; diff --git a/tests/cases/fourslash/referencesBloomFilters2.ts b/tests/cases/fourslash/referencesBloomFilters2.ts index daf60d0dd01..26690e437ee 100644 --- a/tests/cases/fourslash/referencesBloomFilters2.ts +++ b/tests/cases/fourslash/referencesBloomFilters2.ts @@ -3,7 +3,7 @@ // Ensure BloomFilter building logic is correct, by having one reference per file // @Filename: declaration.ts -////var container = { [|{| "isDefinition": true |}42|]: 1 }; +////var container = { [|{| "isWriteAccess": true, "isDefinition": true |}42|]: 1 }; // @Filename: expression.ts ////function blah() { return (container[[|42|]]) === 2; }; @@ -12,7 +12,7 @@ ////function blah2() { container["[|42|]"] }; // @Filename: redeclaration.ts -////container = { "[|{| "isDefinition": true |}42|]" : 18 }; +////container = { "[|{| "isWriteAccess": true, "isDefinition": true |}42|]" : 18 }; const ranges = test.ranges(); const [r0, r1, r2, r3] = ranges; diff --git a/tests/cases/fourslash/referencesBloomFilters3.ts b/tests/cases/fourslash/referencesBloomFilters3.ts index 0dd5c645264..d7d335cde02 100644 --- a/tests/cases/fourslash/referencesBloomFilters3.ts +++ b/tests/cases/fourslash/referencesBloomFilters3.ts @@ -4,7 +4,7 @@ // @Filename: declaration.ts -////enum Test { "[|{| "isDefinition": true |}42|]" = 1 }; +////enum Test { "[|{| "isWriteAccess": true, "isDefinition": true |}42|]" = 1 }; // @Filename: expression.ts ////(Test[[|42|]]); diff --git a/tests/cases/fourslash/referencesForAmbients.ts b/tests/cases/fourslash/referencesForAmbients.ts index 58e4d6e59a5..2397738581e 100644 --- a/tests/cases/fourslash/referencesForAmbients.ts +++ b/tests/cases/fourslash/referencesForAmbients.ts @@ -1,10 +1,10 @@ /// -////declare module "[|{| "isDefinition": true |}foo|]" { +////declare module "[|{| "isWriteAccess": true, "isDefinition": true |}foo|]" { //// var [|{| "isWriteAccess": true, "isDefinition": true |}f|]: number; ////} //// -////declare module "[|{| "isDefinition": true |}bar|]" { +////declare module "[|{| "isWriteAccess": true, "isDefinition": true |}bar|]" { //// export import [|{| "isWriteAccess": true, "isDefinition": true |}foo|] = require("[|foo|]"); //// var f2: typeof [|foo|].[|f|]; ////} @@ -15,7 +15,7 @@ ////} const [moduleFoo0, f0, moduleBar0, foo0, moduleFoo1, foo1, f1, moduleBar1, foo2] = test.ranges(); -verify.singleReferenceGroup('module "foo"', [moduleFoo0, moduleFoo1]); -verify.singleReferenceGroup('module "bar"', [moduleBar0, moduleBar1]); +verify.singleReferenceGroup('module "foo"', [moduleFoo1, moduleFoo0]); +verify.singleReferenceGroup('module "bar"', [moduleBar1, moduleBar0]); verify.singleReferenceGroup('import foo = require("foo")', [foo0, foo1, foo2]); verify.singleReferenceGroup("var f: number", [f0, f1]); diff --git a/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts b/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts index 3e453663f63..448c2627531 100644 --- a/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts +++ b/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts @@ -26,7 +26,7 @@ const methods = ranges.get("method"); const [m0, m1, m2] = methods; verify.referenceGroups(m0, [{ definition: "(method) Base.method(a?: T, b?: U): this", ranges: methods }]); verify.referenceGroups(m1, [ - { definition: "(method) Base.method(): void", ranges: [m0] }, + { definition: "(method) Base.method(a?: T, b?: U): this", ranges: [m0] }, { definition: "(method) MyClass.method(): void", ranges: [m1, m2] } ]); verify.referenceGroups(m2, [ diff --git a/tests/cases/fourslash/referencesForEnums.ts b/tests/cases/fourslash/referencesForEnums.ts index 68face36d04..af4fec8aae8 100644 --- a/tests/cases/fourslash/referencesForEnums.ts +++ b/tests/cases/fourslash/referencesForEnums.ts @@ -2,8 +2,8 @@ ////enum E { //// [|{| "isWriteAccess": true, "isDefinition": true |}value1|] = 1, -//// "[|{| "isDefinition": true |}value2|]" = [|value1|], -//// [|{| "isDefinition": true |}111|] = 11 +//// "[|{| "isWriteAccess": true, "isDefinition": true |}value2|]" = [|value1|], +//// [|{| "isWriteAccess": true, "isDefinition": true |}111|] = 11 ////} //// ////E.[|value1|]; diff --git a/tests/cases/fourslash/referencesForExternalModuleNames.ts b/tests/cases/fourslash/referencesForExternalModuleNames.ts index 5e01eae3530..127aa9fd657 100644 --- a/tests/cases/fourslash/referencesForExternalModuleNames.ts +++ b/tests/cases/fourslash/referencesForExternalModuleNames.ts @@ -3,7 +3,7 @@ // Global interface reference. // @Filename: referencesForGlobals_1.ts -////declare module "[|{| "isDefinition": true |}foo|]" { +////declare module "[|{| "isWriteAccess": true, "isDefinition": true |}foo|]" { //// var f: number; ////} @@ -13,5 +13,4 @@ const ranges = test.ranges(); const [r0, r1] = ranges; -verify.referenceGroups(r0, [{ definition: 'module "foo"', ranges }]); -verify.referenceGroups(r1, [{ definition: 'module f', ranges }]); +verify.referenceGroups(ranges, [{ definition: 'module "foo"', ranges: [r1, r0] }]); diff --git a/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts b/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts index effa4abc164..a869ba8bcc1 100644 --- a/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts +++ b/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts @@ -1,13 +1,13 @@ /// ////class Foo { -//// public [|{| "isDefinition": true |}12|]: any; +//// public [|{| "isWriteAccess": true, "isDefinition": true |}12|]: any; ////} //// ////var x: Foo; ////x[[|12|]]; -////x = { "[|{| "isDefinition": true |}12|]": 0 }; -////x = { [|{| "isDefinition": true |}12|]: 0 }; +////x = { "[|{| "isWriteAccess": true, "isDefinition": true |}12|]": 0 }; +////x = { [|{| "isWriteAccess": true, "isDefinition": true |}12|]: 0 }; //verify.singleReferenceGroup("(property) Foo[12]: any"); const ranges = test.ranges(); diff --git a/tests/cases/fourslash/referencesForStringLiteralPropertyNames.ts b/tests/cases/fourslash/referencesForStringLiteralPropertyNames.ts index e9be352f819..c5ae2f0c586 100644 --- a/tests/cases/fourslash/referencesForStringLiteralPropertyNames.ts +++ b/tests/cases/fourslash/referencesForStringLiteralPropertyNames.ts @@ -1,13 +1,13 @@ /// ////class Foo { -//// public "[|{| "isDefinition": true |}ss|]": any; +//// public "[|{| "isWriteAccess": true, "isDefinition": true |}ss|]": any; ////} //// ////var x: Foo; ////x.[|ss|]; ////x["[|ss|]"]; -////x = { "[|{| "isDefinition": true |}ss|]": 0 }; +////x = { "[|{| "isWriteAccess": true, "isDefinition": true |}ss|]": 0 }; ////x = { [|{| "isWriteAccess": true, "isDefinition": true |}ss|]: 0 }; const ranges = test.ranges(); diff --git a/tests/cases/fourslash/referencesForStringLiteralPropertyNames2.ts b/tests/cases/fourslash/referencesForStringLiteralPropertyNames2.ts index 6fbb0b85072..89b6c7c755e 100644 --- a/tests/cases/fourslash/referencesForStringLiteralPropertyNames2.ts +++ b/tests/cases/fourslash/referencesForStringLiteralPropertyNames2.ts @@ -1,7 +1,7 @@ /// ////class Foo { -//// "[|{| "isDefinition": true |}blah|]"() { return 0; } +//// "[|{| "isWriteAccess": true, "isDefinition": true |}blah|]"() { return 0; } ////} //// ////var x: Foo; diff --git a/tests/cases/fourslash/referencesForStringLiteralPropertyNames3.ts b/tests/cases/fourslash/referencesForStringLiteralPropertyNames3.ts index d4e12a67afc..aae15afd0c7 100644 --- a/tests/cases/fourslash/referencesForStringLiteralPropertyNames3.ts +++ b/tests/cases/fourslash/referencesForStringLiteralPropertyNames3.ts @@ -1,8 +1,8 @@ /// ////class Foo2 { -//// get "[|{| "isDefinition": true |}42|]"() { return 0; } -//// set [|{| "isDefinition": true |}42|](n) { } +//// get "[|{| "isWriteAccess": true, "isDefinition": true |}42|]"() { return 0; } +//// set [|{| "isWriteAccess": true, "isDefinition": true |}42|](n) { } ////} //// ////var y: Foo2; diff --git a/tests/cases/fourslash/referencesForStringLiteralPropertyNames4.ts b/tests/cases/fourslash/referencesForStringLiteralPropertyNames4.ts index efe8972f2c7..4293435de1d 100644 --- a/tests/cases/fourslash/referencesForStringLiteralPropertyNames4.ts +++ b/tests/cases/fourslash/referencesForStringLiteralPropertyNames4.ts @@ -1,6 +1,6 @@ /// -////var x = { "[|{| "isDefinition": true |}someProperty|]": 0 } +////var x = { "[|{| "isWriteAccess": true, "isDefinition": true |}someProperty|]": 0 } ////x["[|someProperty|]"] = 3; ////x.[|someProperty|] = 5; diff --git a/tests/cases/fourslash/renameImportOfExportEquals2.ts b/tests/cases/fourslash/renameImportOfExportEquals2.ts index f57a10c5777..8ac00b8c012 100644 --- a/tests/cases/fourslash/renameImportOfExportEquals2.ts +++ b/tests/cases/fourslash/renameImportOfExportEquals2.ts @@ -8,10 +8,10 @@ ////} ////declare module "a" { //// import * as [|{| "isWriteAccess": true, "isDefinition": true |}O|] from "mod"; -//// export { [|{| "isWriteAccess": true, "isDefinition": true |}O|] as [|{| "isWriteAccess": true, "isDefinition": true |}P|] }; // Renaming N here would rename +//// export { [|O|] as [|{| "isWriteAccess": true, "isDefinition": true |}P|] }; // Renaming N here would rename ////} ////declare module "b" { -//// import { [|{| "isWriteAccess": true, "isDefinition": true |}P|] as [|{| "isWriteAccess": true, "isDefinition": true |}Q|] } from "a"; +//// import { [|P|] as [|{| "isWriteAccess": true, "isDefinition": true |}Q|] } from "a"; //// export const y: typeof [|Q|].x; ////} diff --git a/tests/cases/fourslash/renameImportOfReExport2.ts b/tests/cases/fourslash/renameImportOfReExport2.ts index 56cc3966112..ac61200b2f0 100644 --- a/tests/cases/fourslash/renameImportOfReExport2.ts +++ b/tests/cases/fourslash/renameImportOfReExport2.ts @@ -4,7 +4,7 @@ //// export class [|{| "isWriteAccess": true, "isDefinition": true |}C|] {} ////} ////declare module "b" { -//// export { [|{| "isWriteAccess": true, "isDefinition": true |}C|] as [|{| "isWriteAccess": true, "isDefinition": true |}D|] } from "a"; +//// export { [|C|] as [|{| "isWriteAccess": true, "isDefinition": true |}D|] } from "a"; ////} ////declare module "c" { //// import { [|{| "isWriteAccess": true, "isDefinition": true |}D|] } from "b"; diff --git a/tests/cases/fourslash/renameJsExports01.ts b/tests/cases/fourslash/renameJsExports01.ts index b731ece63f3..e1b71d232a6 100644 --- a/tests/cases/fourslash/renameJsExports01.ts +++ b/tests/cases/fourslash/renameJsExports01.ts @@ -2,7 +2,7 @@ // @allowJs: true // @Filename: a.js -////exports.[|area|] = function (r) { return r * r; } +////exports.[|{| "isWriteAccess": true, "isDefinition": true |}area|] = function (r) { return r * r; } // @Filename: b.js ////var mod = require('./a'); diff --git a/tests/cases/fourslash/server/convertFunctionToEs6Class-server.ts b/tests/cases/fourslash/server/convertFunctionToEs6Class-server.ts new file mode 100644 index 00000000000..9ab47086f20 --- /dev/null +++ b/tests/cases/fourslash/server/convertFunctionToEs6Class-server.ts @@ -0,0 +1,25 @@ +// @allowNonTsExtensions: true +// @Filename: test123.js + +/// + +//// // Comment +//// function fn() { +//// this.baz = 10; +//// } +//// /*1*/fn.prototype.bar = function () { +//// console.log('hello world'); +//// } + +verify.applicableRefactorAvailableAtMarker('1'); +verify.fileAfterApplyingRefactorAtMarker('1', +`// Comment +class fn { + constructor() { + this.baz = 10; + } + bar() { + console.log('hello world'); + } +} +`, 'Convert to ES2015 class'); diff --git a/tests/cases/fourslash/shims-pp/getPreProcessedFile.ts b/tests/cases/fourslash/shims-pp/getPreProcessedFile.ts index 03ce481c8ba..a33a6c9a470 100644 --- a/tests/cases/fourslash/shims-pp/getPreProcessedFile.ts +++ b/tests/cases/fourslash/shims-pp/getPreProcessedFile.ts @@ -5,12 +5,12 @@ //// class D { } // @Filename: refFile2.ts -//// export class E {} +//// export class E {} // @Filename: main.ts // @ResolveReference: true //// /// -//// /*1*/////*2*/ +//// /// //// /*3*/////*4*/ //// import ref2 = require("refFile2"); //// import noExistref2 = require(/*5*/"NotExistRefFile2"/*6*/); diff --git a/tests/cases/fourslash/shims/getPreProcessedFile.ts b/tests/cases/fourslash/shims/getPreProcessedFile.ts index 03ce481c8ba..a33a6c9a470 100644 --- a/tests/cases/fourslash/shims/getPreProcessedFile.ts +++ b/tests/cases/fourslash/shims/getPreProcessedFile.ts @@ -5,12 +5,12 @@ //// class D { } // @Filename: refFile2.ts -//// export class E {} +//// export class E {} // @Filename: main.ts // @ResolveReference: true //// /// -//// /*1*/////*2*/ +//// /// //// /*3*/////*4*/ //// import ref2 = require("refFile2"); //// import noExistref2 = require(/*5*/"NotExistRefFile2"/*6*/); diff --git a/tests/cases/fourslash/signatureHelpImportStarFromExportEquals.ts b/tests/cases/fourslash/signatureHelpImportStarFromExportEquals.ts new file mode 100644 index 00000000000..cdf4b0a5c64 --- /dev/null +++ b/tests/cases/fourslash/signatureHelpImportStarFromExportEquals.ts @@ -0,0 +1,15 @@ +/// + +// @allowJs: true + +// @Filename: /node_modules/@types/abs/index.d.ts +////declare function abs(str: string): string; +////export = abs; + +// @Filename: /a.js +////import * as abs from "abs"; +////abs/**/; + +goTo.marker(); +edit.insert('('); +verify.currentSignatureHelpIs('abs(str: string): string'); diff --git a/tests/cases/fourslash/transitiveExportImports3.ts b/tests/cases/fourslash/transitiveExportImports3.ts index 6b3bb10572d..638fa85df83 100644 --- a/tests/cases/fourslash/transitiveExportImports3.ts +++ b/tests/cases/fourslash/transitiveExportImports3.ts @@ -4,7 +4,7 @@ ////export function [|{| "isWriteAccess": true, "isDefinition": true |}f|]() {} // @Filename: b.ts -////export { [|{| "isWriteAccess": true, "isDefinition": true |}f|] as [|{| "isWriteAccess": true, "isDefinition": true |}g|] } from "./a"; +////export { [|f|] as [|{| "isWriteAccess": true, "isDefinition": true |}g|] } from "./a"; ////import { [|{| "isWriteAccess": true, "isDefinition": true |}f|] } from "./a"; ////import { [|{| "isWriteAccess": true, "isDefinition": true |}g|] } from "./b"; diff --git a/tests/cases/fourslash/tsxGoToDefinitionClassInDifferentFile.ts b/tests/cases/fourslash/tsxGoToDefinitionClassInDifferentFile.ts new file mode 100644 index 00000000000..7aa1c11fdc3 --- /dev/null +++ b/tests/cases/fourslash/tsxGoToDefinitionClassInDifferentFile.ts @@ -0,0 +1,15 @@ +/// + +// @jsx: preserve + +// @Filename: C.tsx +////export default class /*def*/C {} + +// @Filename: a.tsx +////import C from "./C"; +////const foo = ; + +verify.noErrors(); + +goTo.marker("use"); +verify.goToDefinitionIs("def"); diff --git a/tests/cases/fourslash/tsxQuickInfo6.ts b/tests/cases/fourslash/tsxQuickInfo6.ts index e121e52c0aa..2b65dc7667a 100644 --- a/tests/cases/fourslash/tsxQuickInfo6.ts +++ b/tests/cases/fourslash/tsxQuickInfo6.ts @@ -14,6 +14,6 @@ //// } verify.quickInfos({ - 1: "function ComponentSpecific<{}>(l: {\n prop: {};\n}): any", - 2: "function ComponentSpecific<{}>(l: {\n prop: {};\n}): any" + 1: "function ComponentSpecific(l: {\n prop: number;\n}): any", + 2: "function ComponentSpecific(l: {\n prop: U;\n}): any" }); diff --git a/tests/cases/fourslash/tsxQuickInfo7.ts b/tests/cases/fourslash/tsxQuickInfo7.ts index ca90d83d719..cf08aa53e98 100644 --- a/tests/cases/fourslash/tsxQuickInfo7.ts +++ b/tests/cases/fourslash/tsxQuickInfo7.ts @@ -15,15 +15,15 @@ //// let a3 = ; //// let a4 = ; //// let a5 = ; -//// let a6 = ; +//// let a6 = ; //// } verify.quickInfos({ - 1: "function OverloadComponent(): any (+2 overloads)", - 2: "function OverloadComponent(): any (+2 overloads)", - 3: "function OverloadComponent(): any (+2 overloads)", - 4: "function OverloadComponent(): any (+2 overloads)", + 1: "function OverloadComponent(attr: {\n b: number;\n a?: string;\n \"ignore-prop\": boolean;\n}): any (+2 overloads)", + 2: "function OverloadComponent(attr: {\n b: string;\n a: boolean;\n}): any (+2 overloads)", + 3: "function OverloadComponent(attr: {\n b: string;\n a: boolean;\n}): any (+2 overloads)", + 4: "function OverloadComponent(attr: {\n b: number;\n a?: string;\n \"ignore-prop\": boolean;\n}): any (+2 overloads)", 5: "function OverloadComponent(): any (+2 overloads)", 6: "function OverloadComponent(): any (+2 overloads)", - 7: "function OverloadComponent(): any (+2 overloads)" + 7: "function OverloadComponent(): any (+2 overloads)", }); diff --git a/tests/cases/fourslash/untypedModuleImport.ts b/tests/cases/fourslash/untypedModuleImport.ts index 4dac6ac76bb..5501cec4792 100644 --- a/tests/cases/fourslash/untypedModuleImport.ts +++ b/tests/cases/fourslash/untypedModuleImport.ts @@ -17,6 +17,6 @@ const [r0, r1, r2] = test.ranges(); verify.singleReferenceGroup('"foo"', [r1]); goTo.marker("foo"); -verify.goToDefinitionIs([]); +verify.goToDefinitionIs("foo"); verify.quickInfoIs("import foo"); verify.singleReferenceGroup("import foo", [r0, r2]); diff --git a/tests/lib/react.d.ts b/tests/lib/react.d.ts index 1d7b787b999..7f03899eb6c 100644 --- a/tests/lib/react.d.ts +++ b/tests/lib/react.d.ts @@ -197,7 +197,7 @@ declare namespace __React { type SFC

= StatelessComponent

; interface StatelessComponent

{ - (props: P, context?: any): ReactElement; + (props: P & { children?: ReactNode }, context?: any): ReactElement; propTypes?: ValidationMap

; contextTypes?: ValidationMap; defaultProps?: P;